3

I am trying to use local storage in nextjs with redux, I know that With Next.js, components are rendered server-side. localStorage - or the window - is not available until rendered in a browser. That's why I used this typeof window !== "undefined"; Now the error is showing Hydration failed because the initial UI does not match what was rendered on the server.

import { createSlice } from "@reduxjs/toolkit";
const clientSide = typeof window !== "undefined";

const initialState = {
  cart: clientSide
    ? localStorage.getItem("cartItems")
      ? JSON.parse(localStorage.getItem("cartItems") || "{}")
      : []
    : [],
  cartTotal: 0,
  cartTotalQuantity: 0,
};
Jerin
  • 717
  • 1
  • 7
  • 28
  • The solution for this question might fix your problem [NextJs LocalStorage](https://stackoverflow.com/questions/54819721/next-js-access-localstorage-before-rendering-page) – Sadra M. May 02 '22 at 08:48
  • 1
    This example shows how to integrate Redux with the power of Redux Persist in Next.js.: https://stackoverflow.com/questions/63276931/load-the-initial-state-with-localstorage-redux-next-js – Oleg May 02 '22 at 08:54
  • Not able to solve the issue, can any one help me with code – Jerin May 02 '22 at 17:35

1 Answers1

0

I think you can call useEffect() on your index page or wherever , then in the hook dispatch an action to update the initial state.

walid
  • 5
  • 2