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

268
Views
React JS: remove an item from the localStorage

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));
  })

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>

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);
  })

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 = [];

Thanks for any help regarding the situation!

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

0

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

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!