preserving the current state even after refreshing the page

  • Currently, I am teaching myself React.
  • When I click on the favorites button, which is represented by a heart symbol, it changes color.
  • However, upon refreshing the page, the color change disappears.
  • To address this issue, I came across the following helpful link: How to maintain state after a page refresh in React.js?
  • After implementing the solution, I can now see the local storage in the developer tools application tab.
  • Despite these changes, the color is still not retained upon page refresh.
  • While debugging, I noticed that nothing is being printed in getInitialState. Could this be causing the problem?
  • Can you provide guidance on how to fix this issue so that I can learn to handle it myself in the future?
  • I have also included my relevant code snippet and sandbox below.
  • All of my code can be found in RecipeReviewCard.js

https://codesandbox.io/s/xrp56z04yq

  getInitialState = () => {
    var addFavorite = localStorage.getItem("AddFavorite") || 1;
    console.log("getInitialState--->", addFavorite);

    return {
      addFavorite: addFavorite
    };

    //this.setState(state => ({ belowExpanded: !state.belowExpanded }));
  };


<FavoriteIcon
              style={{ display: this.state.addFavorite ? "none" : "" }}
              onClick={e => {
                console.log("favoriteEvent---.", e);
                console.log(
                  "this.state.addFavorite---.",
                  this.state.addFavorite
                );

                localStorage.setItem("AddFavorite", !this.state.addFavorite);
                this.setState({ addFavorite: !this.state.addFavorite });

                console.log(
                  "!this.state.addFavorite---.",
                  !this.state.addFavorite
                );

                this.props.onAddBenchmark(this.props);
              }}
            />

Answer №1

According to the documentation on LocalStorage syntax, it is necessary to stringify the addFavorite before setting it in local storage. When retrieving the value in componentDidMount, you can parse it back to its original form within getInitialState.

For instance, you might do the following:

localStorage.setItem(JSON.stringify(!this.state.addFavorite)) // for example "true" or "false"

and retrieve it as:

getInitialState = () => {
  let fav = localStorage.getItem('AddFavorite');
  let addFavorite = JSON.parse(fav || "true");
  this.setState({ addFavorite });
}

Just a tip: It's advisable to set localStorage in componentWillUnmount if possible without causing any issues. Utilizing local storage and performing JSON serialization can impact performance.

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

Why is the validate function not being executed in the Backbone Model?

I am a beginner in learning Backbone and I am attempting to implement simple validation in my Person Model. However, I am facing an issue where the validate method does not run when I set a new age. Can someone guide me on where I might be making a mistake ...

What is the best way to provide a service to a React <Route>?

I am looking to pass some data to my React Routes using Provider and my other stores. <Router> <Routes> <Provider store={store}> <Route path="/" element={HomePage} /> </Provider> <P ...

Connecting JSON objects based on unique GUID values generated

I am in search of a method to automate the laborious task of linking multiple JSON objects with random GUIDs. The JSON files are all interconnected: { "name": "some.interesting.name", "description": "helpful desc ...

Enhance your user interface by adding a tooltip above a button

I am currently working on creating a button that can copy content from a variable into the clipboard using TypeScript and Material-UI. Here is what I have tried: const [copySuccess, setCopySuccess] = useState(''); const copyToClipBoard = async ( ...

When evaluating objects or arrays of objects to determine modifications

How can we detect changes in table data when users add input to cells? For example, if a user clicks on a cell and adds an input, the function should return TRUE to indicate that there are changes. If the user just clicks on the cell without making any ch ...

Utilizing ReactJS to implement real-time form validation using Material UI

Currently, I am facing the challenge of validating a form. Below is the minimal reproducible version of my form. The form is built using React's Material UI. import React from 'react'; import TextField from '@material-ui/core/TextFiel ...

What's the best way to determine which of the two forms has been submitted in Django?

On my homepage, I have both a log_in and sign_up form. Initially, the log_in form is displayed by default, but when a user clicks on the Sign Up button, the sign_up form appears. These toggles switch depending on which button the user clicks. from django ...

How can I use JQuery to save values from a for loop?

After working on a grid, I encountered an issue where only the last value was being returned when trying to fetch all values into an object. Unfortunately, I am stuck and unsure of how to resolve this problem. function item_details(){ var gridDataAr ...

React's custom fetch hook falls short by one pace

After diving into the world of creating custom fetch hooks for both get and post data, I found myself facing a common issue - my hook-returned state variables seemed to always be one step behind due to the asynchronous behavior of useState. Here is the cus ...

How to override an event in JavaScript when a specific value is entered

I am looking to implement a system with complex conditions. The goal is to have an alert appear when a value is inputted and the button is clicked. First, a confirmation message Have you input ? should be displayed, followed by clicked with input. If no va ...

What is the best technique to position a div at the bottom of a container that has a height of 100

After many attempts and searching for answers, I'm still struggling to figure out how to make the div float to the bottom with 100% height. I've even considered if it's an issue with Pure or something else entirely. It's definitely frus ...

Unexpected behavior with scrollTop

Note Reopening bounty as I forgot to award it last time. This question has already been answered by Master A.Woff. I am looking for a way to automatically scroll to a specific row when a user expands it, so that the content is immediately visible witho ...

Track user sessions and transfer username to final page

Is there a way to showcase the chosen username from a dropdown menu on the initial page and then also display it on the last page without having to pass variables between pages? Additionally, if I wish to incorporate a timer on a middle page, how can I sto ...

I am facing an issue with my Angular 11 CLI application while trying to set it up with Jest. The specific error message I am encountering is: "TypeError: Cannot read property

Having issues with my Angular 11 cli app and Jest integration. Whenever I run npm run test, specifically jest --updateSnapshot, I encounter the following error in my terminal: Error: TypeError: Cannot read property 'paths' of undefined Here is ...

Tips on aligning text to the left on mobile devices using CSS and HTML

When viewed on a standard 16:9 computer screen, everything looks perfect with text on the left and an image on the right. However, when it comes to smaller screens like phones, the picture appears on top of the paragraph instead. I am new to this, so any a ...

Sometimes, Express may return the message "not found" on and off

After working with express for many years, I find myself a bit out of practice with TypeScript - and it seems like my eyesight is failing me! This is the first time I've encountered this issue, so I must be missing something... My current dilemma is ...

Set the GridToolbarQuickFilter text box to have an outlined style in Material UI v5

How can I customize the appearance of the GridToolbarQuickFilter textbox, such as outlining it? Ideally, I would like to accomplish this through theme.tsx, but I am open to any suggestions. https://i.stack.imgur.com/H1Ojj.png I have experimented with var ...

Gatsby MDX fails to locate the desired page despite displaying the title and slug

Currently diving into the world of Gatsby and I've decided to implement MDX for my blog pages. Following a helpful tutorial here on programmatically creating pages. All seems well as I can view them in my GraphQL and displaying the list of articles i ...

The way images appear can vary between desktop and mobile devices

I am in the process of creating a photography website with a simple goal of displaying images down the page one after another. However, I am encountering issues with uniform display across various desktop and mobile platforms. The site appears perfect on i ...

Navigate through a React interface with a Node.js backend routing system

As I embark on the journey of building a web application, I find myself facing some confusion. How can I effectively handle both React routing and Node routing? Is there a way to configure them to run on the same port? What is the best approach for imple ...