I am trying to make a cart based ecommerce website. I am using Redux and Redux Toolkit to simplify things. I am fairly new to this and my code is not working as expected.
I am trying to dispatch data to state but the state does not update. Redux Devtools show that data is being indeed dispatched to store, but the state remains the same.
In the action, I am console logging the state items and I think the problem lies here which I can't understand.
import { createSlice } from "@reduxjs/toolkit";
let initialState = [
{
name: "",
id: "",
quantity: "",
mode: "",
bookType: "",
},
];
const cartSlice = createSlice({
name: "cart",
initialState,
reducers: {
add: (state, action) => {
return state.map((item) => {
console.log(item);
if (item.id !== action.payload.id) {
return item;
}
return {
...item,
added: true,
};
});
},
remove: (state, action) => {
return state.map((item) => {
if (item.id !== action.payload.id) {
return item;
}
return {
...item,
added: false,
};
});
},
},
});
export const { add, remove } = cartSlice.actions;
export const getCart = (state) => state.cart;
export default cartSlice.reducer;
This is how I am dispatching in my code:
function formSubmit(event) {
event.preventDefault();
const requiredCourse = courses[0];
const dispatchItem = {
name: requiredCourse.name,
id: requiredCourse.id,
quantity: 1,
mode: mode,
bookType: bookType,
};
if (userLoggedIn) {
console.assert("About to dispatch");
dispatch(add(dispatchItem));
setTimeout(() => {
Router.push("/cart");
}, 2000);
} else {
openModal();
setTimeout(() => {
Router.push({
pathname: "/user/signup",
query: {
redirect: requiredCourse.url,
},
});
}, 6000);
}
}
Every help is really appreciated.