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

176
Visualizações
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 Respostas
Responde à pergunta

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 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