mardag
mardag

Reputation: 41

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?

Upvotes: 0

Views: 1137

Answers (1)

Dharmik Patel
Dharmik Patel

Reputation: 1201

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

Upvotes: 2

Related Questions