Reputation: 351
My reducer removeMovie
is not working. Every time I get all initial data from state without one element. I need to update state on every call.
import { createSlice } from '@reduxjs/toolkit';
import movies from '../../services/movies.json';
export const movieSlice = createSlice({
name: 'movie',
initialState: movies,
reducers: {
addMovie: (state, action) => {
state.push(action.payload);
},
removeMovie: (state, action) => {
state = state.filter(movie => movie.title !== action.payload);
console.log(JSON.stringify(state));
},
},
});
// Action creators are generated for each case reducer function
export const { addMovie, removeMovie } = movieSlice.actions;
export default movieSlice.reducer;
Upvotes: 1
Views: 1875
Reputation: 401
What you are doing in removeMovie reducer is not tracked by Immer library. With this line state = state.filter(movie => movie.title !== action.payload);
you are assigning local state variable, and that is not actually change of state. You can try this:
removeMovie: (state, action) => {
const newState = state.filter(movie => movie.title !== action.payload);
console.log(JSON.stringify(newState));
return newState;
},
You can find more about this on the following link: immer usage patterns
Upvotes: 4