Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
localStorage values are set to undefined after refreshing the page

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;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda