reactjsnext.jslocal-storagereferenceerror

Server error: ReferenceError (localstorage) is not defined (Nextjs)


I have a category name stored in my localstorage. I understand that with nextjs, localstorage is only stored on the browser, and not in the server side. I've tried this thanks to what I have read of stackoverflow questions with similar issues, but I'm still getting ReferenceError: selectedCategoryName is not defined:

import React, { useState, useEffect } from 'react';

const sets = () => {
    if (typeof window !== 'undefined'){
        let selectedCategoryName = localStorage.getItem('selectedCategoryName');
        console.log(selectedCategoryName)
    }
    return (
        <div className="title">
            <h2>{selectedCategoryName}</h2> //server error
        </div>
    )
}

I've also tried this instead of the if statement (not confident this is right anyway), but same error:

useEffect(() => { 
    const categoryNameTitle = localStorage.get('selectedCategoryName');

    if(categoryNameTitle) {
      setMyState((prev) => ({ ...prev, selectedCategoryName: JSON.parse(categoryNameTitle)}))
    }
  }, [])

Solution

  • You get an undefined selectedCategoryName because it only exists in the scope of your if(...){...} block.

    The code below should works better:

    const sets = () => {
      const selectedCategoryName = typeof window !== 'undefined' 
        ? localStorage.getItem('selectedCategoryName') 
        : undefined;
      console.log(selectedCategoryName)
       
      return (
        <div className="title">
          <h2>{selectedCategoryName}</h2>
        </div>
      )
    }