Reputation: 321
I'm trying write reducer for ticket object in my app and I use createSlice for it like this:
export const ticketSlice = createSlice({
name: 'ticket',
initialState: { value: null },
reducers: {
ticketSet: (state, action) => {
state.value = action.payload;
},
ticketSetCategory: (state, action) => {
state.value.category = action.payload;
}
}
});
Everything works fine but it's not so convenient to use state.ticket.value in useSelector. I prefer state.ticket instead it. So I changed my reducer like it:
export const ticketSlice = createSlice({
name: 'ticket',
initialState: {},
reducers: {
ticketSet: (state, action) => {
state = action.payload;
},
ticketSetCategory: (state, action) => {
state.category = action.payload;
}
}
});
After that, the storage stopped working. The ticket value is always an empty object. What am I doing wrong?
Upvotes: 1
Views: 809
Reputation: 67539
state = anything
is never a valid statement in an Immer-powered reducer, because it is neither mutating the state, nor returning a new value.
The short answer is that you want return action.payload
here to replace the existing state.
For more details, see the extended writeup on this topic in our docs:
https://redux-toolkit.js.org/usage/immer-reducers#resetting-and-replacing-state
Upvotes: 1