Home > Blockchain >  how can i check if an item does not exist before adding it to Array of items in Redux
how can i check if an item does not exist before adding it to Array of items in Redux

Time:05-22

am trying to check if an item is not in an items Array before adding it, but am get an error TypeError: Cannot read properties of undefined (reading 'indexOf') please am i doing wrong here, can someone help me out.

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

const initialState = {
  items: [],
};

export const basketSlice = createSlice({
  name: 'basket',
  initialState,
  reducers: {
    addToBasket: (state, action) => {
      let prevItems = state.items.indexOf(action.payload) > -1;
      let newItems = [...state.items];

      if (prevItems) {
        newItems = newItems.filter((id) => id !== action.payload);
      } else {
        newItems.push(action.payload);
      }

      return {
        ...state.items,
        newItems,
      };
    },
  },
});

export const { addToBasket } = basketSlice.actions;

export const selectItems = (state) => state.basket.items;

export default basketSlice.reducer;

CodePudding user response:

I think the problem is with your return statement. Because it overwrites the whole state with the object.


return {
    items: newItems
};

CodePudding user response:

Try this solution.

let items=['1','2','3']
let newItems=[];
if (!items.includes(action.payload) || items.length==0 ) {
  // if item does not exists then add that item OR if items array is empty
  const newArr = [...items,action.payload]
  newItems.push(newArr);
} else {
  // else return actual array
  newItems = items;
}
return newItems;
  • Related