Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

91
Vistas
Functions is executed before the data is taken from state in React Javascript

So when the visitors visits for the first time, if they don't have those information I require on the localStorage, it should set them then fetch the data. But the problem is it shows as null when I fetches the data. I tried async but I don't know.

So basically I want all of the localStorage and state to be set before the getData functions is runned.

useEffect(() => {
    (async function () {
      try {
        if (localStorage.getItem('language') === null) {
          localStorage.setItem('language', 'en');
          setLanguage('en')
        }

        if (localStorage.getItem('view') === null) {
          localStorage.setItem('view', 'verses');
          setView('verses');
        }

         getData(`${view}_${language}`);

      } catch (e) {
        console.error(e);
      }
    })();
  }, []);

Here is the function it calls:

const getData = async (where) => {
    try {
      const { data: content, error } = await supabase
        .from(where)
        .select('*')
      if (error) throw error;
      if (content) {
        const randomizer = content[Math.floor(Math.random() * content.length)];
        setContent(randomizer);
      }
    } catch (error) {
      alert(error.error_description || error.message)
    } finally {
      // console.log(content.content)
    }
  }

and here are the states:

  const [view, setView] = useState(null);
  const [language, setLanguage] = useState(null);
  const [content, setContent] = useState(null);
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Doesn't matter if you keep them inside the async, the state update itself is async, perhaps you can do the following:


const [language, setLanguage] = useState(localStorage.getItem('language')  || 'en');

useEffect(() => {
    localStorage.setItem('language', language); 
}, [language])

// and same for view 

useEffect(() => {
   if(language && view) {
      getData(`${view}_${language}`);
   }
}, [language, view]) 

I assume these states, language and view, are changed somehow in your app, otherwise you most likely don't need to keep them in state.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda