React JS tutorial: deleting an entry from the browser's localStorage

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!

Answer №1

The issue seems to be related to the use of

localStorage.removeItem(key, jokesJsonified);
For removeItem, only the key should be specified, not the value.

In addition, there is an unnecessary rerender when setting the jokes array. Consider using jokes array as a ref instead of state.

Check out this working example on codesandbox

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What strategies can I use to organize and fuse together my library?

I am intrigued by the concept of modular JS and have decided to create my own small library to experiment with it. Here is my vision for how I want it to function: It will include 5 methods Users can download a full library that exports a global variab ...

The gradual vanishing of principles

Below you will find text fields that I am populating with values that are later utilized in a JavaScript function. These fields are all contained within a form. The issue I am encountering is that when I submit the form, I initially get the correct value ...

What is the best way to customize the appearance of a toggle switch using useStyles in Material UI, rather than withStyles?

I need help with customizing the styling of an input form switch in Material UI. I want the track and button to turn red when the switch is on, similar to this example. I have tried using the withStyles method following examples on the Material UI website, ...

What advantages does em have over px in the Zurb Foundation's responsive grid system?

The Zurb Foundation Media Queries are specified in em units: $small-range: (0em, 40em); /* 0, 640px */ $medium-range: (40.063em, 64em); /* 641px, 1024px */ $large-range: (64.063em, 90em); /* 1025px, 1440px */ $xlarge-range: (90.063em, 120em); /* 1441px, 1 ...

What is the best way to trigger the jQuery-File-Upload event within this function?

Before uploading a file, I want to check the API first. $('.file_upload_button_wrapper').on('click', function () { // perform check here $.ajax({ url: '/?app=files&getfile=ajax%2Fupload.php', ...

What is the definition of 'rejected' in relation to Deferred objects aside from jqXHRs?

Exploring the deferred.fail() method on this page: Overview: This method allows you to add handlers that will be executed if the Deferred object is rejected. Here's an example: $.get("test.php") .done(function(){ alert("$.get succeeded"); }) .fai ...

Any modifications made to a copied object will result in changes to the original object

The original object is being affected when changes are made to the cloned object. const original = { "appList": [{ "appId": "app-1", "serviceList": [{ "service": "servic ...

What is the best way to showcase the information of each object on a click event in Vue.js?

My goal with this code is to display each day's class schedule when it is clicked on. However, the issue I'm facing is that the entire week's schedule is being displayed instead of just the selected day. What adjustments should I make in ord ...

Creating a personalized theme for Material UI 5.0 using Typescript with React

Having some trouble customizing a theme in Material UI 5.0 with typescript. theme.ts import { createTheme } from '@mui/material'; declare module '@mui/material/styles' { interface Theme { custom: { buttonWi ...

sidebar that appears upon the initial page load

I'm currently working on implementing a sidebar navigation panel for my website using JavaScript, HTML, and CSS. However, I am facing an issue where the sidebar automatically opens when the page is first loaded, even before clicking on the icon to ope ...

Creating a centered horizontal line in a table cell using CSS

element, imagine placing a line in the middle of a table cell (td) like this: To achieve this effect, you can insert a line within the td as shown in the image below: This allows you to write text while keeping the line visible in the background, almost ...

jQuery functionality restricted to desktop devices

I am attempting to disable a jQuery function specifically for mobile devices. I found some instructions that seem helpful on this page. Unfortunately, following the instructions did not work for me. Here is the code snippet I have: var isMobile = /Androi ...

Automatically populating additional fields in JavaScript/React by taking information from the initial field

1. I am working with an array called "listOfPaysIndexes", which contains 12 indexes. My goal is to use this array to iterate through and display 12 DateInput fields. 2. Each of these fields can be clicked on to select a date. 3. Once a date is chosen in ...

How come CSS styles are not being applied to forms in AngularJS?

When attempting to apply CSS styles to a form in order to indicate invalid input, I encountered an issue. Even after using the important tag, the styles did not change. I created a dynamic form from JSON and now need to validate it. Following a suggestion ...

Expanding an array in JavaScript

I need assistance with... let a = ['a', 2, 3]; a += function(){return 'abc'}; console.log(a[3]); Therefore, I am looking for a shorthand method to push() in array with the above content. Does anyone know of an operator that can help ...

Vue's Global mixins causing repetitive fires

In an effort to modify page titles, I have developed a mixin using document.title and global mixins. The contents of my mixin file (title.ts) are as follows: import { Vue, Component } from 'vue-property-decorator' function getTitle(vm: any): s ...

Issues with the orderBy function are causing unexpected behavior

After creating 3 groups - priority 1, 2, and 3 with orderBy:priorty for each pushed task to go into their designated group, I noticed some strange behavior within the groups where they don't sort properly when more data is added. <input ng-model=" ...

I am having trouble getting the filter functionality to work in my specific situation with AngularJS

I inserted this code snippet within my <li> tag (line 5) but it displayed as blank. | filter: {tabs.tabId: currentTab} To view a demo of my app, visit http://jsfiddle.net/8Ub6n/8/ This is the HTML code: <ul ng-repeat="friend in user"> ...

Retrieve the $.data() value from within a specific selector

I'm facing an issue with the following code snippet: <img class="sth" data-number="1" src="sth.jpg" alt=""> In my project, there are multiple elements similar to this one, all differing only in the value of data-number attribute. I want to per ...

Obtain the information sent by the Jquery ajax call

Below is the code snippet in question: $.ajax({ type: 'GET', data: { s: sToSearch }, url: 'http://localhost:9809/handlers/search.ashx', }).done(function (d) { sCache[sToSearch.toLowerCase()] = d; showResult(d); }); ...