Local storage is not defined

Viewed 16404

How can I get values from local storage in next.js?When i give localStorage.getItem() in console,it is prnting the values.But when I assign this to a variable it is giving LocalStorage is not defined error.I have also added redux-persist in my localstorage

localStorage.getItem('id')

4 Answers

Local Storage is a Web API native to modern web browsers. It allows websites/apps to store data in the browser, making that data available in future browser sessions. There are two React lifecycle methods we can use in our component to save/update the browsers localStorage when the state changes:

componentDidMount()
componentDidUpdate()

componentDidMount will run once your component has become available and loaded into the browser. This is when we gain access to localStorage. Since localStorage doesn’t reside in Node.js/Next.js since there is no window object, we will have to wait until the component has mounted before checking localStorage for any data. So If you want to assign the local storage value into a variable, please do this inside the componentDidMount method.

componentDidMount() {
    const data = localStorage.getItem('id')
    console.log(data);
    if(data) {
      //here you can set your state if it is necessary
    }
  }

And If we want to update our local storage value through the state we can easily update the localStorage value with our changes value by using componentDidUpdate. This method gets run each time the state changes so we can simply replace the data in localStorage with our new state.

componentDidUpdate() {
    localStorage.setItem('id', JSON.stringify(this.state))  
  }

localStorage is a property of object window. It belongs to the browser, not next.js nor React, and accessing localStorage is not possible until React component has been mounted. So you need to ensure that your React app is mounted before calling localStorage, e.g. calling localStorage.getItem inside componentDidMount.

When working with a framework like Next.js that executes code on the server side, using localStorage produces an error like "localStorage is not defined" or "window is not defined"

To fix this, check to see if window is defined so that the code will run only when it's available.

This is a great article that explains more: https://blog.logrocket.com/using-localstorage-react-hooks/ See the section called, "Problems accessing localStorage for an SSR application"

You can create a file called "useLocalStorage.tsx" or whatever, and it would contain something like this:

import { useState, useEffect } from "react";

function getStorageValue(key, defaultValue) {
  // getting stored value
  if (typeof window !== 'undefined') {
const saved = localStorage.getItem(key);
return saved || defaultValue;
  }
}

export const useLocalStorage = (key, defaultValue) => {
  const [value, setValue] = useState(() => {
return getStorageValue(key, defaultValue);
  });

  useEffect(() => {
// storing input name
localStorage.setItem(key, value);
  }, [key, value]);

  return [value, setValue];
};

Then you can just import it into the file you want to use it in like this:

import { useLocalStorage } from './useLocalStorage'

Then you can call it to get the "id" from localStorage:

const [id, set_id] = useLocalStorage("id", "");

First think to take a note is, localStorage has nothing to do with next.js or redux-persist. localStorage is the internal window object and can be directly accessible without any definition.

I think you are trying to access the localStorage before it is being set, so you get that error.

Simple solution to this is to use Conditional (ternary) operator ,

const id = localStorage.getItem('id') ? localStorage.getItem('id') : "set your own default value";
console.log(id);
Related