I’m making a Shopping List App with React/Redux. I’m having truble removing an item from a list. After excecuting the ‘removeItem’ action the page can no longer read the object that is the list (which was previously stored in local state and coul’d be read before excecuting the action).
I’ve tried storing the list object in a const variable and a local state using the useEffect hook but it still breaks.
JSX
const { id } = useParams();
const shoppingLists = useSelector((state) => state.shoppingLists);
const findList = shoppingLists.find((list) => list.listId === id);
const [selectedList, setSelectedList] = useState({});
useEffect(() => {
setSelectedList(findList);
});
const removeItemForm = (item) => {
const { itemName, itemId } = item;
dispatch(removeItem({ itemName, itemId, listId: id }));
};
<div className="listHeading mb-4">
<h2>{selectedList.listName}</h2> //Line that breaks
</div>
Reducer
const shoppingListsSlice = createSlice({
name: "shoppingLists",
initialState: [],
reducers: {
createList(state, action) {
state.push({
listId: uuidv4(),
listName: action.payload,
items: [],
color: "",
createdAt: Date(),
});
addItem(state, action) {
state
.find((list) => list.listId === action.payload.listId)
.items.push({
itemId: uuidv4(),
itemName: action.payload.itemName,
isBought: false,
});
},
removeItem(state, action) {
return state
.find((list) => list.listId === action.payload.listId)
.items.filter((item) => item.itemId !== action.payload.itemId);
},