Home > front end >  LocalStorage not updated with the latest value
LocalStorage not updated with the latest value

Time:07-11

I am new to react and I am experimenting with incrementing a value and storing it into local storage. I was able to write down the following code bellow, however, the last instance of the incremented number is not updated the local storage value. For example, if I press " 1" twice and the number is 10, the dom is updated twice and shows the number 12, but the value stored on local storage is 11. Why is this happening?

import { useState } from 'react'


function About () {

    const localStorageValue = parseInt(localStorage.getItem('value'))
    const [value, setValue] = useState(localStorageValue);

    function remove() {
        setValue((add) => add - 1)
        localStorage.setItem('value', parseInt(value))
    }

    function add() {
        setValue((add) => add   1)
        localStorage.setItem('value', parseInt(value))
    }


    return (
        <>
            <h1>About page</h1>

            <button onClick={remove}>-1</button>
            {value}
            <button onClick={add}> 1</button>
        </>
    )
}

export default About;

CodePudding user response:

Use the refresh button and it will reflect the changes

enter image description here

CodePudding user response:

Issue here is asynchronous behaviour of setState i.e. it will update the state value with a bit of delay and without stopping for complete execution of setState it will proceed to next line of code i.e. localStorage.setItem().

In your case setState is setValue

So to overcome this you can need some kind of callback function behaviour to achieve this with useState hook so you can use useEffect for the same as follows:

import { useState, useEffect } from "react";

function About() {
    const localStorageValue = parseInt(localStorage.getItem("value"));
    const [value, setValue] = useState(localStorageValue);

    useEffect(() => {
        localStorage.setItem("value", parseInt(value));
    }, [value]); // only rerun if value changes

    function remove() {
        setValue((add) => add - 1);
    }

    function add() {
        setValue((add) => add   1);
    }

    return (
        <>
            <h1>About page</h1>

            <button onClick={remove}>-1</button>
            {value}
            <button onClick={add}> 1</button>
        </>
    );
}

export default About;

This will ensure that it will run everytime after successive state update.

PS. There's no need to use parseInt while storing as it will be stored as string only.

  • Related