Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!