So i am working o an ecommerce website and i am using redux to manage state of my cart . as i add items to the cart is is stored in my redux slice . when i console.log this state.items
i see an array of items added to my cart . once i refesh my check out page , all my items added to the cart dissappears . here is the code belew
REDUX SLICE
import { createSlice } from "@reduxjs/toolkit";
import Items from "../app/Items";
const initialState = {
items: [],
};
export const basketSlice = createSlice({
name: "basket",
initialState,
reducers: {
addToBasket: (state, action) => {
state.items = [...state.items, action.payload]
state.items
},
removeFromBasket:(state, action) =>{
console.log(action , "jhj");
let newBasket = state.items.filter(({id}) => id != action.payload.id);
state.items = newBasket;
}
},
});
export const { addToBasket, removeFromBasket } = basketSlice.actions;
// Selectors - This is how we pull information from the Global store slice
export const selectItems = (state) => state.basket.items;
export const selectTotal = (state) => state.basket.items.reduce((total, item) =>
total + item.price, 0);
export default basketSlice.reducer;
CHECKOUT CART
On refesh the state clears up
import { useSelector } from "react-redux";
import Header from "../components/Header";
import CheckoutProduct from "../components/CheckoutProduct";
import { selectItems, selectTotal } from "../slices/basketSlice";
import Currency from "react-currency-formatter";
import { signIn, signOut, useSession } from "next-auth/client"
function Checkout() {
const items = useSelector(selectItems);
const total = useSelector(selectTotal)
const [session] = useSession();
// {!session ? 'Sign in to checkout' : "Proceed to checkOut"}
return (
<div >
<Header />
<main >
<h1 className="text-center">YOUR LUXURY WEAR CART</h1>
<div className="grid grid-flow-row-dense md:grid-cols-2 lg:grid-cols-3">
{items.map((item, id) => (
<CheckoutProduct
id={id}
key={id}
name={item.name}
price={item.price}
size={item.size}
image={item.image}
/>
))}
</div>
<br/>
<br/>
<br/>
<div className="flex sub ml-16 items-center bg-white shadow-md">
{items.length > 0 && (
<>
<h2>Subtotal
( {items.length} items)
<span>
<Currency quantity={total} currency="GBP" /> </span> </h2>
<button role="link"
onClick={signIn} className={`button mt-2 font-semibold pl-5 pr-5 `}>
SIGN IN
</button>
<button
disabled={!session} className={`button mt-2 ${!session && 'from-gray-300 to-gray-500 border-gray-200 text-gray-300 cursor cursor-not-allowed'}`}
>
{!session ? "signin to checkout" : "Pay with card"}
</button>
</>
)}
</div>
</main>
</div>
)
}
export default Checkout