简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM