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

99
Views
Store data from json to localStorage browser

I'm trying to make a program where you get from an API, and every 3 seconds you get a new value, so far so good, I get the value using useEffect/useState.

const [data, setData] = useState();
    useEffect(() =>{
        const interval = setInterval(() => {
          getData()
        },3000);
        return () => clearInterval(interval);
      },[])
      //fetch the data function
      const getJoke = (() => {
        fetch('API URL')
        .then((res) => res.json())
        .then((res) => {
          setData(res.value);
        })
        .catch((err) => console.log(err));
      })

So everything work fine with this, I get the data appear every 3 seconds

<button id="button" onClick = {handleGetT}>{isActive ? 'Get Data' : 'Stop'}</button>
        <h3>{isActive ? null : data}</h3>

But I'm really struggling to save the like as favourite. I have an other button where when you click it you save it on the localstorage browser data.

<button id="button" onClick = {localStorage.setItem("name",data)}>Save!</button>

I know the above may not be appropriate way of doing it, for some reason I get different data saved on localstorage every 3 seconds, and I would like to save the when clicked the joke that appears, on lets say an array, so I could use it later to print it.

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

0

The function in onClick runs itself every time the button is rendered. You need to wrap it in an anonymous function like this:

<button id="button" onClick={()=>{localStorage.setItem("name",data)}}>Save!</button>

More info: https://stackoverflow.com/a/33846760/9224578

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!