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

171
Vistas
How to render components based on localStorage value

How do I render based on the data in the localStorage? The localStorage has a key-value pair (location: US or Location: AU) and is added when the user visits.

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

let localUserLoc = userLoc;  //works fine when I set this variable to 'US' or 'AU'

const LoadSections= (props) => {
  const { sections, className } = props;

  const [userLoc, setUserLoc] = useState(JSON.stringify(localStorage.getItem('userLoc')) || '');

  useEffect(() => {
    const userLoc = JSON.stringify(localStorage.getItem('userLoc'));
    setUserLoc(userLoc);
  }, []);

  useEffect(() => {
    getUserLoc = userLoc;
  }, [userLoc]);

  // // console.log(local1, 'outside');
  console.log(abTestType, '4 - outside');


  return (

    <Wrapper className={className}>

      {sections.map((section, sectionIndex) => {

        const userLocProp = section.userLoc;


        if (userLocProp === localUserLoc) {

          return <SomeComp />
        }

        else if (userLocProp === 'undefined') {
          return <AnotherComp />
        }

The code above only loads the if I manually set the localUserLoc to 'US' or 'AU'. However, when I try to update the variable from localStorage it doesn't display .

I think it is because the LocalStorage is read but not rendered? I tried using two UseEffect hooks and added the first one as a dependency but to no avail.

How can I read and then set the localUserLoc variable to whatever it is in the localStorage and render the relevant component?

  • The user loc is detected via IP and then I setItem in localStorage.
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It doesn't work because you are using JSON.stringify after getting the value from localStorage but the value stored in localStorage is already a string because localStorage can only store string values.

So you have to use JSON.parse for getting the value from localStorage and convert it to a javascript object.

const [userLoc, setUserLoc] = useState(JSON.parse(localStorage.getItem('userLoc'))
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