Ghost Ghost
Ghost Ghost

Reputation: 81

How do I persist my redux state with local storage

So I am working o an e-commerce website and I am using Redux to manage the state of my cart. As I add items to the cart it 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 dissappear. here is the code below.

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

Upvotes: 2

Views: 7794

Answers (1)

nart
nart

Reputation: 1848

Redux is an in-memory state management so when you refresh page the state will lost. In order to persist the state to localStorage you can use redux-persist Config you store file

import { combineReducers, configureStore } from '@reduxjs/toolkit'
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from 'redux-persist'
import storage from 'redux-persist/lib/storage'

import rootReducer from './reducers'

const persistConfig = {
  key: 'root',
  version: 1,
  storage,
  blacklist: ['counter'] // What you don't wanna to persist
  whitelist: ['auth'] // What you want to persist
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
})

export const persistor = persistStore(store)

In your root index.js

import { PersistGate } from 'redux-persist/integration/react'
import { store, persistor } from './redux/store'
import App from './App'

ReactDOM.render(
  <Provider store={store}>
    <PersistGate loading={<div>loading...</div>} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>,
  document.getElementById('root')
)

Upvotes: 2

Related Questions