I am currently working on an App that fetches data from an API and updates it randomly every 3 seconds. The user has the ability to print the data by clicking a button, which can also be used to stop the random updates. I have managed to implement this functionality using React.js:
useEffect(() =>{
const interval = setInterval(() => {
getJoke()
},3000);
return () => clearInterval(interval);
},[])
//fetch the jokes function
const getJoke = (() => {
fetch('https://api.chucknorris.io/jokes/random')
.then((res) => res.json())
.then((res) => {
setKey(res.id);
setJoke(res.value);
})
.catch((err) => console.log(err));
})
I have also implemented a button that allows the user to save the randomly generated data to the browser's localStorage:
const addJokeFav = (() => {
jokes.push(joke);
const jokesJsonified = JSON.stringify(jokes);
localStorage.setItem(key, jokesJsonified);
})
below the render code
<button id="button" onClick={()=>{addJokeFav()}}>Save!</button>
However, I am now looking for a way to enhance this feature by having only one button that saves the random data every 3 seconds. If the user clicks the button again, the data should be removed from the localStorage. I have tried implementing a function for this purpose:
const remJokeFav = (() => {
const jokesJsonified = JSON.stringify(jokes);
localStorage.removeItem(key, jokesJsonified);
})
Unfortunately, I am encountering an issue where the function is attempting to remove an item that does not exist due to the key value, which I retrieve using setKey(res.id) in the initial snippet of code above. Below are the variables used in my App:
const [joke, setJoke] = useState();
const [key, setKey] = useState([]);
const [isActive, setActive] = useState("false");
const jokes = [];
Any assistance with resolving this issue would be greatly appreciated!