I want to reset state using below code. But I don't know why it gives me the error 'initialState' is not defined. Please help me to solve this problem. Thanks a lot.
import { createSlice } from '@reduxjs/toolkit';
const cartSlice = createSlice({
name: 'cart',
initialState:
// JSON.parse(localStorage.getItem('item')) ||
{
products: [],
quantity: 0,
total: 0,
},
reducers: {
addProduct: (state, action) => {
state.products.push(action.payload);
state.quantity = 1;
state.total = action.payload.price * action.payload.quantity;
// localStorage.setItem('item', JSON.stringify(state));
},
deleteItem: (state, action) => {
state.quantity -= 1;
state.total -= action.payload.price * action.payload.quantity;
},
reset: (state) => {
state = initialState;
},
},
});
export const { addProduct, reset, deleteItem } = cartSlice.actions;
export default cartSlice.reducer;
CodePudding user response:
You have not initialized the initialState at all. You could pull the initialState out of the slice and it should work.
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
products: [],
quantity: 0,
total: 0,
};
const cartSlice = createSlice({
name: 'cart',
initialState:
// JSON.parse(localStorage.getItem('item')) ||
initialState
reducers: {
addProduct: (state, action) => {
state.products.push(action.payload);
state.quantity = 1;
state.total = action.payload.price * action.payload.quantity;
// localStorage.setItem('item', JSON.stringify(state));
},
deleteItem: (state, action) => {
state.quantity -= 1;
state.total -= action.payload.price * action.payload.quantity;
},
reset: (state) => {
state = initialState;
},
},
});
export const { addProduct, reset, deleteItem } = cartSlice.actions;
export default cartSlice.reducer;
CodePudding user response:
You have to manually declare the initial state to reset the state .
import { createSlice } from '@reduxjs/toolkit';
const cartSlice = createSlice({
name: 'cart',
initialState:
// JSON.parse(localStorage.getItem('item')) ||
{
products: [],
quantity: 0,
total: 0,
},
reducers: {
addProduct: (state, action) => {
state.products.push(action.payload);
state.quantity = 1;
state.total = action.payload.price * action.payload.quantity;
// localStorage.setItem('item', JSON.stringify(state));
},
deleteItem: (state, action) => {
state.quantity -= 1;
state.total -= action.payload.price * action.payload.quantity;
},
reset: (state) => {
state = {
products: [],
quantity: 0,
total: 0,
};
},
},
});
export const { addProduct, reset, deleteItem } = cartSlice.actions;
export default cartSlice.reducer;
CodePudding user response:
state = something
never works in RTK reducers. You can modify the object in the variable state
, you cannot reassign the variable state
to a new object.
Do return something
instead of state = something
. This is described in the Writing Reducers with immer
documentation page.