Home > Mobile >  Server error: ReferenceError (localstorage) is not defined (Nextjs)
Server error: ReferenceError (localstorage) is not defined (Nextjs)

Time:09-11

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)}))
    }
  }, [])

CodePudding user response:

Looks like you are using "localstorage" somewhere else. Read the error message carefully.

ReferenceError (localstorage) is not defined

it is not saying localStorage with capital "S" it says localstorage with lowercase "s". looks like you used localstorage somewhere else which is undefined

or when you write this

let selectedCategoryName = localStorage.getItem('selectedCategoryName');

localStorage has no 'selectedCategoryName' record. you conditionally set with ternary operator

let selectedCategoryName = localStorage.getItem('selectedCategoryName') ? localStorage.getItem('selectedCategoryName') :
"this data does not exist"

CodePudding user response:

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>
  )
}
  • Related