I just learned redux and tried to create a simple store app with React Redux. everything was fine until I try to combine reducers
When i click to clear cart, I got an error "TypeError: Assignment to constant variable"
here is my code before
index.js
function cartReducer(state, action) {
switch (action.type) {
case ADD_TO_CART: {
return {
cart: [
...state.cart,
{
product: action.productInfo,
quantity: action.quantity,
},
],
};
}
case CLEAR_CART: {
const new_state = { ...state };
new_state.cart = [];
return new_state;
}
default:
return state;
}
}
store.js
function loadState(){
try{
const state = localStorage.getItem('cart');
if(state !== null){
return JSON.parse(state);
}
} catch(e){
// ignore errors
}
return {
cart: []
};
}
const store = createStore(
cartReducer,
loadState(),
compose(
applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
and here is after combine reducers
index.js
export default function cartReducer(state, action) {
switch (action.type) {
case ADD_TO_CART: {
return [
...state,
{
product: action.productInfo,
quantity: action.quantity
}
]
}
case CLEAR_CART: {
const new_state = [...state];
new_state = [];
return new_state;
}
default:
{
if (state === undefined)
return [];
return state;
}
}
}
store.js
function loadState(){
try{
const state = localStorage.getItem('cart');
if(state !== null){
return JSON.parse(state);
}
} catch(e){
// ignore errors
}
return {
cart: []
};
}
const appReducers = combineReducers({
cart: cartReducer,
});
const store = createStore(
appReducers,
loadState(),
compose(
applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
CodePudding user response:
case CLEAR_CART: {
const new_state = [...state]; // new_state is a constant
new_state = []; // you can not assign it again
return new_state;
}
// TO FIX IT:
case CLEAR_CART: {
return []; // that's enough
}
CodePudding user response:
case CLEAR_CART: {
const new_state = [...state]; //clone
new_state = [];
return new_state;
}
The problem is that you are overwriting the "const new_state"
case CLEAR_CART: {
return [];
}
Try this instead.