localdata01
localdata01

Reputation: 657

react native redux toolkit filter not working

why is my filter function not working ?

ShipperSlice.js

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

const createProductShipper = createSlice({
  name: "createProductShipper",
  initialState: {
    shippers: []
  },
  reducers: {
    AddProductShipper: (state, action) => {
      const shipperExists = state.shippers.find(el => el?.id === action.payload.id);
      if(typeof shipperExists !== 'undefined') {
        return state.shippers.filter(el => el.id !== action.payload.id);
      } else {
        state.shippers.push(action.payload)
      }
      console.log(current(state.shippers));
    },
  }
});

export const { AddProductShipper, RemoveProductShipper } = createProductShipper.actions;

export default createProductShipper.reducer;

This is the push output

Array [
  Object {
    "id": 1,
    "shipper": "SHIPPER",
  },
]

If shipper exists then I get this error: .................

TypeError: undefined is not an object (evaluating 'state.shippers.find')

Why my shippers object removes ?

The State:
Object {
  "shippers": Array [],
}
First Click: 
Object {
  "shippers": Array [
    Object {
      "id": 1,
      "shipper": "DHL",
    },
  ],
}
Second Click:
Array []

.....................................................

Upvotes: 1

Views: 328

Answers (1)

Vasyl Nahuliak
Vasyl Nahuliak

Reputation: 2468

Change return state.shippers.filter(el => el.id !== action.payload.id);

To: state.shippers = state.shippers.filter(el => el.id !== action.payload.id);

Upvotes: 1

Related Questions