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));
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
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>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
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.
CodePudding user response:
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