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

320
Views
In react, how can I store data immediately if there's none and use it right away?

I'm having trouble using LocalStorage data.

I used storejs (localStorage library), therefore store.getItem equals to localStorage.getItem and store.setItem equals to localStorage.setItem.

please check my code.


const test = () => {

  useEffect(() => {
    const res = store.getItem('data')

    // I'm trying toexecutes following code if store returns undefined.
    if(!res) {
      store.setItem('data', [{name:'aden', age:17}])
      store.getItem('data')
    }
  },[])

return <></>

}

I know this code doesn't work. However, What I'm trying to do is when component mounts and there's nothing in LocalStorage, I want to immediately setItem to LocalStorage, and fetch the item right away.

However, with that code, I get nothing from the LocalStorage, It seems like I'm having misconception on lifecycle of react.

How can I solve the problem?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Try this:

import React, { useState } from "react";

const Test = () => {
  const [user, setUser] = useState(JSON.parse(localStorage.getItem("user")));

  const addToLocalStorage = () => {
    const payload = [{ name: "aden", age: 17 }];
    setUser(payload);
    localStorage.setItem("user", JSON.stringify(payload));
  };

  return (
    <>
      <div>
        {user?.length > 0 &&
          user.map((e) => <span key={e.name}>name:{e.name}</span>)}
      </div>
      <button onClick={addToLocalStorage}>Add to localStorage</button>
    </>
  );
};

export default Test;

about 4 years ago · Juan Pablo Isaza Report

0

useEffect(() => { const res = store.getItem('data')

// I'm trying toexecutes following code if store returns undefined.
if(!res) {
  store.setItem('data', [{name:'aden', age:17}])
  store.getItem('data')
}

},[]) Maybe you should type store.setItem

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!