Home > database >  persist username value after page refresh in React using local storage
persist username value after page refresh in React using local storage

Time:10-16

I am trying to set and retrieve the value of username using localstorage. When the page loads, the user should see a heading that says welcome John. And when the page reloads, I need the value to persist.

But when I load the page, I get the error message username is not defined. This is the code, what am I missing?

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

const UserHeading = () => {
  const [user, setUser] = useState("john")

  useEffect(() => {
JSON.parse(localStorage.getItem(user)) || [];
  })

  useEffect(() => {
    localStorage.setItem(username, JSON.stringify(user));
  }, [user]);
console.log(user)
  const userid = JSON.parse(localStorage.getItem(user)) 
  console.log(userid)

  return <h1> Welcome {userid} </h1>;
};

export default UserHeading;

CodePudding user response:

change your component like this :

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

const UserHeading = () => {
const [user, setUser] = useState("john")

  useEffect(() => {
    localStorage.setItem('username', JSON.stringify(user)); //changed
  }, [user]);
console.log(user)
  const userid = JSON.parse(localStorage.getItem('username')) //changed
  console.log(userid)

  return <h1> Welcome {userid} </h1>;
};
export default UserHeading;
  • Related