Home > Blockchain >  React JS: remove an item from the localStorage
React JS: remove an item from the localStorage

Time:11-30

I'm trying to make a workable App where you get from an API some data and that data is randomly changes every 3 seconds and with a button the user can print the data and by pressing again it stops, i have managed to complete this(as seen bellow) part(btw new to 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));
  })
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

i have also made a button where the user can save the data(which randomly appears every 3 sec) on the localStorage of the browser as seen bellow..

const addJokeFav = (() => {
    jokes.push(joke);
    const jokesJsonified = JSON.stringify(jokes);
    localStorage.setItem(key, jokesJsonified);
  })
  
  bellow the render code
  
  <button id="button" onClick={()=>{addJokeFav()}}>Save!</button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

but i would like to have only one button where he save one data coming randomly and every 3 seconds, and if he repress the button the data will be deleted from the localStorage. i have this function here which i dont seem to make it work.

const remJokeFav = (() => {
    const jokesJsonified = JSON.stringify(jokes);
    localStorage.removeItem(key, jokesJsonified);
  })
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

it seems that is trying to remove and item that is not there cause of the key, which i take it with setKey(res.id) on the response, on the code above in the first snippet. my App variables are bellow.

const [joke, setJoke] = useState();
  const [key, setKey] = useState([]);
  const [isActive, setActive] = useState("false");
  const jokes = [];
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Thanks for any help regarding the situation!

CodePudding user response:

The problem looks to be with localStorage.removeItem(key, jokesJsonified); removeItem just needs the key and not the value.

Also there is unnecessary rerender on setting jokes array. Make jokes array as ref instead of state.

Here is an working example in codesandbox

  • Related