NextJS issue reading items already in local storage

Viewed 581

On logging into my NextJS application, I am saving some user data to local storage.

I am trying to render this into a small component which always displays the users name. The issue i am getting is that it is only sometimes showing and other times it is displaying as null ... It seems when i log in, it displays as null, but when i reload the page it works.

This is what I have;

import { useEffect } from 'react';

export default function ProfileDisplay() {
    useEffect(async () => {
        const userName = JSON.parse(localStorage.getItem('profile'));
        console.log(userName);
    }, []);

    return (
        <div>
            {userName}
        </div>
    )
}
2 Answers

It is probably coming as null initially because on your server side there is no "localStorage" object. And since you are calling useEffect with empty dependency array , it will not fire when username changes. So you should declare username outside the useEffect and put it in dependency array for listening to changes.

export default function ProfileDisplay() {
  const userName = JSON.parse(localStorage.getItem('profile')); // moved it outside the useEffect 
  useEffect(() => {
    if(userName)
      console.log(userName); // do stuff with username
    
}, [userName]); // it will fire when username changes

return (
    <div>
        {userName}
    </div>
)
}

You can put the userName variable in state and update it in your useEffect once its value is retrieved from localStorage.

import { useEffect, useState } from 'react';

export default function ProfileDisplay() {
    const [userName, setUserName] = useState('')

    useEffect(() => {
        const profile = JSON.parse(localStorage.getItem('profile'));
        setUserName(profile);
    }, []);

    return (
        <div>{userName}</div>
    )
}
Related