i have tried all i could, i could get a solution, i need my count value to remain, even if i refresh my page. for example if my count is up to 3, and when i refresh my browser, the 3 should remain and not start from zero.
can i get any help?? i am currently learning localstorage
here is the code
import React, { useState } from "react";
export default function LocalStorageSetting() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount((prevCount) => prevCount 1);
};
localStorage.setItem("count", count);
return (
<div>
<button onClick={handleClick}>Increase</button>
<h1>{count}</h1>
</div>
);
}
CodePudding user response:
Read it when you set the initial value
const [count, setCount] = useState( (localStorage.count || 0));
CodePudding user response:
@epascarello's answer works. You could also use the setCount function you created.
const [count, setCount] = useState(0);
setCount(localStorage.getItem("count") ?? 0);
Also note that localStorage
stores string key/value pairs. count
should have something like .toString()
on the end when adding it as the value. So use localStorage.setItem("count", count.toString())
.
CodePudding user response:
You can start your state using the value stored in Local Storage, this way, the value count will init by LS value. Keep in mind that Local Storage saves your value as string
, so you need to parse the value before init to be sure that your value will be typed as Number
const [count, setCount] = useState(Number(localStorage.count || 0));
Something I like to do it keep the value save in the save function that changed the value, keeping the value changes in a single function.
const handleClick = () => {
setCount((prevCount) => prevCount 1);
localStorage.setItem("count", count);
};