Home > Software engineering >  localStorage values are set to undefined after refreshing the page
localStorage values are set to undefined after refreshing the page

Time:06-06

I am trying to integrate previous information from localStorage into the DOM so the user can see it after re-visiting the page in the same browser. For some reason, reloading sets the major and declared properties in localStorage to undefined.

Could anyone tell me why this is happening and how I can fix it? Here is my code:

import React, { useState, useReducer, useEffect, useRef } from "react";
import MajorStatus from "./MajorStatus";
import ClassType from "./ClassType";
import styles from "/styles/ClassSearch.module.css";

function UserInfo() {
  const [currentMajor, setCurrentMajor] = useState();
  const [currentlyDeclared, setIsCurrentlyDeclared] = useState();

  useEffect(() => {
    localStorage.setItem("declared", currentlyDeclared);
    localStorage.setItem("major", currentMajor);
  }, [currentMajor, currentlyDeclared]);

  useEffect(() => {
    let storedDeclarationStatus = localStorage.getItem("declared");
    let storedMajor = localStorage.getItem("major");
    let declarationLabel = storedDeclarationStatus ? "Declared" : "Undeclared";
    declaredRef.current.setValue({
      label: declarationLabel,
      value: storedDeclarationStatus,
    });
    majorRef.current.setValue({
      label: storedMajor,
      value: storedMajor,
    });
  }, []);

  let declaredRef = useRef();
  let majorRef = useRef();

  function onChangeMajorHandler(userInput) {
    setCurrentMajor(userInput.value.major);
    console.log("Current input major: "   userInput.value.major);
  }

  function onChangeDeclaredHandler(userInput) {
    setIsCurrentlyDeclared(userInput.value.declared);
    console.log("Current input declaration: "   userInput.value.declared);
  }

  function onSubmitHandler(event) {
    event.preventDefault();
  }

  return (
    <form className={styles.userInfo} method="post" onSubmit={onSubmitHandler}>
      <MajorStatus
        onChangeMajorHandler={onChangeMajorHandler}
        onChangeDeclaredHandler={onChangeDeclaredHandler}
        majorRef={majorRef}
        declaredRef={declaredRef}
      />
      <ClassType />
      <button
        type="submit"
        name="submitUserInfo"
        className={styles.submitUserInfoButton}
      >
        Search
      </button>
    </form>
  );
}

export default UserInfo;

CodePudding user response:

The problem is caused by the first useEffect, it's running before the second one when the component gets mounted, and it's setting the values in localStorage to the initial values of your states, undefined since you didn't set any when calling useState. One way to avoid this issue is:

useEffect(() => {
  if (currentlyDeclared) {
    localStorage.setItem("declared", currentlyDeclared);
  }
  if (currentMajor) {
    localStorage.setItem("major", currentMajor);
  }
}, [currentMajor, currentlyDeclared]);
  • Related