0

Does anyone know how to check if an object is inside an array, and if so, update it?

I tried the find method but when I do, it says it can't find the object I'm referring to. I also tried includes but for some reason it too doesn't think the item is in the array.

This is the best I got:

import { createSlice, PayloadAction } from "@reduxjs/toolkit";

interface Displate {
  name: string;
  finish: string;
  size: string;
  frame: string;
  price: number;
  quantity: number;
}

interface DisplateArray extends Array<Displate> {}

const initialState: DisplateArray = [];

export const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addDisplate: (state, action: PayloadAction<Displate>) => {
      state.map((displate) => {
        if (displate.name === action.payload.name) {
          return displate.quantity++;
        } else {
          return state.push(action.payload);
        }
      });
    },
  },
});

export const { addDisplate } = cartSlice.actions;

export default cartSlice.reducer;

But this just adds a new object everytime

0

1 Answer 1

1

It seems that the quantity is not updated because state.map does not mutate the updated quantity back to the proxy state for an update.

Assuming that the goal is to check item with same name in the state array, if item exists add 1 to its quantity, and if not add a new object fromaction.payload to the array, consider to use find as a condition instead (using Immer update from Redux Toolkit):

export const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addDisplate: (state, action: PayloadAction<Displate>) => {
      const existingItem = state.find(
        (item) => item.name === action.payload.name
      );
      if (!existingItem) {
        state.push({ ...action.payload, quantity: 1 });
        return;
      }
      existingItem.quantity++;
    },
  },
});
Sign up to request clarification or add additional context in comments.

2 Comments

This works thanks! How would you remove an item btw? Assuming the payload was a string? state.filter(item => item.name !== action.payload)?
@ether Thanks for the feedback, for removing I think first check existingItem.quantity and do existingItem.quantity-- if .quantity is more than 1, or if quantity is at 1 then do state = state.filter((item) => item.name !== action.payload.name) to remove the item should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.