Home > Mobile >  how to fix localStorage is not defined in react js and how to set and get Item back
how to fix localStorage is not defined in react js and how to set and get Item back

Time:11-11

why localStorage is not defined

  const [bookmark, setBookmark] = useState([]);
  const { showBookmark, setShowBookmark } = useContext(Context);

  const addToBookmark = (id) => {
    if (!bookmark.includes(id)) setBookmark(bookmark.concat(id));
  };

  const removeBookmark = (id) => {
    let index = bookmark.indexOf(id);
    let temp = [...bookmark.slice(0, index), ...bookmark.slice(index   1)];
    setBookmark(temp);
  };
  let findBookmark = data1.ayat.filter((e) => bookmark.includes(e.nomor));

  useEffect(() => {
    localStorage.setItem('list', JSON.stringify(findBookmark));
  }, [findBookmark]);

  findBookmark = JSON.parse(localStorage.getItem('list')) || '[]';

So, I want to make bookmark feature in my project where I get the data from data1. When I click addBookmark it will save data as per id to localStorage and it works, but when I use getItem from localStorage errors appear:

ReferenceError: localStorage is not defined

and then findBookmark.map()

CodePudding user response:

The issue you are seeing is because localStorage, which is an alias for window.localStorage, is not defined on the server side. A server renders your components, so when that happens, and it tries to access localStorage it can't find it. You'll have to wait until the browser renders it in order to use localStorage.

localStorage will have the value (window object) after the useEffect() runs. You can test it using the code snippet below inside the useEffect() hook.

if (typeof window !== 'undefined') {
  console.log('You are on the browser')
  //            
  • Related