Home > Blockchain >  Checking array for object before updating it in redux
Checking array for object before updating it in redux

Time:01-22

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

CodePudding user response:

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  ;
    },
  },
});
  • Related