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

Identifying Flash content in a unique way

In my dynamic page (let's call it myFlashContainer.jsp), the Flash content changes based on the link that is clicked. The code responsible for rendering the Flash looks like this: <object height="100%" align="l" width="100%" id="player" codebase= ...

"Enhance user experience with jQuery's text expansion and collapse

Figuring out how to collapse and expand text with a button click has been challenging for me. I managed to make the text collapse when the button is clicked, but now I also need it to expand back again. The goal is to have the text initially hidden, then e ...

Having trouble updating my account after failing to meet a login rule with NextAuth Google provider

Currently, I am integrating NextAuth with the Google Provider and have implemented a feature based on their provided example. The example allows for domain verification during login authentication, where users with an email domain that does not match the s ...

Show identification as an alternative term in the chart

Is there a way to display an id in a table cell as another name from a different object with corresponding ids? I want to achieve something like this if it's possible: <td class="tableRowText"><p>{{l.SenderId}}</p></td> simil ...

PHP: When MySQL is not returning results and an undefined variable is causing issues

Currently, I am engaged in a project where I need to fetch some data from the database and display it within a form. Although my SQL query seems correct when reviewed in the SQL log, MySQL is not returning any results. I am seeking assistance on how to ret ...

Getting an Object in PostgreSQL without the need for square brackets wrapping when using Node.js and Express

I'm currently utilizing PostgreSQL alongside node-postgres: pool, Node.js, and express to execute some basic queries. The issue I encounter is that the returned object is wrapped within square brackets, but my preference is to receive it without them. ...

MUI Modal overlay for stylish Ionic select dialogues

In my react application, I am utilizing the MUI library, but there are instances where I still need to incorporate Ionic framework in the code. ISSUE: When opening MUI modal windows that contain Ionic selects, the select modals end up being covered by the ...

Issue with the Material UI theme module enhancement feature not functioning as expected

I've been researching the MUI documentation, blogs, and various posts on Stackoverflow, but despite my efforts, I can't seem to get my vscode intellisense/typescript to recognize the changes I've made. These are fairly straightforward modif ...

The CSS 'top' attribute is without impact

As I begin my journey with CSS, I am eager to grasp some of its behaviors. In the CSS file, the following code is defined: #spa { position : absolute; top : 8px; left : 8px; bottom : 8px; right : 8px; min-height : 500px; min-width : 500px ...

Breaking down and analyzing XML information

I have data that I need to retrieve from an XML file, split the result, parse it, and display it in an HTML element. Here is a snippet of the XML file: <Root> <Foo> <Bar> <BarType>Green</BarType> &l ...

Setting the backEnd URL in a frontEnd React application: Best practices for integration

Hey there - I'm new to react and front-end development in general. I recently created a RESTful API using Java, and now I'm wondering what the best way is to specify the backend URL for the fetch() function within a .jsx file in react. Currently, ...

Leveraging ng-selected in AngularJS to effortlessly select multiple options from a collection

Two arrays of objects are causing me some confusion, with one array being a subset of the other: $scope.taskGroups = [ {id: 1, name: 'group1', description: 'description1'}, {id: 2, name: 'group2', description: 'descr ...

The for loop encountered an uncaught type error when trying to access the .length property

Currently, I am working on a school project where the task is to create a basic social network posting application using Django and JavaScript. The purpose of using JavaScript is to dynamically load posts onto the webpage and update HTML components. I have ...

Best practices for selecting checkboxes and transferring values to another page in PHP/HTML

Apologies for my lack of experience in PHP. I am in the process of creating a project without any knowledge of PHP. I have set up a database with a list of users and can display users based on specific information through a search. Each search query has a ...

Verify if the value of localStorage matches the specified value, then conceal the element

This is my second query and I'm hoping it covers everything. My knowledge of javascript is limited, which has made it difficult for me to get my code working properly. Despite trying various different approaches, I have been unable to resolve the issu ...

Is it possible to conceal JavaScript comments on a page before it is displayed?

Curiosity has led me to ponder a question that may seem trivial. Consider this scenario: in my HTML or ASPX page, I include a comment for some JavaScript code. When the page loads, will the comments be rendered along with the rest of the page's conten ...

Can you offer guidance on how to include a MUI icon as a React component?

I am looking to utilize a custom name for the mui-icon component in order to have more control over its function. Due to implementation requirements, I need to choose a different name from the default one assigned to the icon. // Default import import ...

Covering a secret link with a backdrop image

I have set a background image in a column on my WordPress site. However, I want to make this image clickable by placing a transparent box over it, as background images cannot be linked directly. #container { background-image: url(https://www.quanser.c ...

Automating item selection using Selenium in Python

Currently, I am in the process of developing a software program to automate web database management. However, I have encountered an issue while trying to manipulate a table where I need to arrange the items based on one of the columns by clicking on the co ...

Custom virtual properties can be set in Mongoose by utilizing the return value in a callback function

I've been searching all over for a solution to my issue, but I can't seem to find the right answer. I'm currently using MongooseJS as my ODM and I'm attempting to create virtual getters that can retrieve, process, and display informatio ...