Home > other >  Removing one object from an array by its id, react.js
Removing one object from an array by its id, react.js

Time:02-03

Ok so basically I am trying to remove one object from an array by its id.

meat-context.js

import React, { useReducer, useState } from "react";

const MeatContext = React.createContext({ meatState: [] });

export function MeatContextProvider(props) {
  const meatReducer = (state, action) => {
    if (action.type === "ADD_MEAT") {
      return [...state, action.payload];
    }
    if (action.type === "REMOVE_MEAT") {
      for (var i = 0; i < state.length; i  ) {
        if (state[i].id == action.payload) {
          console.log(state[i].id);

          state.splice(i, 1);
          break;
        }
        console.log(state);
        console.log(action.payload);
        return state;
      }
    }
    return [];
  };

  const [meatState, dispatchMeatState] = useReducer(meatReducer, []);
  const [showModal, setShowModal] = useState(false);

  if (showModal) {
    document.body.style.overflow = "hidden";
  }

  return (
    <MeatContext.Provider
      value={{
        meatState: meatState,
        dispatchMeatState: dispatchMeatState,
        showModal: showModal,
        setShowModal: setShowModal,
      }}
    >
      {props.children}
    </MeatContext.Provider>
  );
}
export default MeatContext;

the goal is to remove an object through the action "REMOVE_MEAT" but somehow the condition if (state[i].id == action.payload) is apparently never met and therefore the object is never removed. The console.log(state) prints

[
    {
        "name": "Sushi",
        "description": "Finest fish and veggies",
        "price": 22.99,
        "id": "m1"
    },
    {
        "name": "Sushi",
        "description": "Finest fish and veggies",
        "price": 22.99,
        "id": "m1"
    }
]

for example(after clicking remove)

and console.log(action.payload) prints

{
    "id": "m1"
} 

the condition should be then met but is never is console.log(state[i].id) nor the rest of the condition body ever runs. Any idea?

CodePudding user response:

Your condition is state[i].id == action.payload, where state[i].id is always a string and action.payload is always an object shaped like

{
    id: string
}

The condition is always false since no string will strictly equal an object. You'll need to write state[i].id == action.payload.id instead to compare the ids.

  •  Tags:  
  • Related