I was trying to get the total value of marks on a table of student exam scores. On save changes I get the correct value. But on browser refresh the value to 0. I used useEffect()
and useMemo()
hooks but kept getting the same result. But I used normal variable, (not useState()
hook), the values stays even after refresh.
Here is the code.
const englishSubmitted = JSON.parse(
localStorage.getItem("englishSubmitted") as string
);
const [englishResult, setEnglishResult] = useState<
{ [key: string]: string }[]
>([]);
useEffect(() => {
if (englishSubmitted) {
setEnglishResult(
JSON.parse(localStorage.getItem("englishAnswers") as string)
);
}
},[])
`// this does not work`
useEffect(() => {
const value = englishResult.reduce((acc, current) => {
acc = parseInt(current.marks);
return acc;
}, 0);
setEnglishMarks(value);
}, []);
`//this does not work either`
useMemo(() => {
const value = englishResult.reduce((acc, current) => {
acc = parseInt(current.marks);
return acc;
}, 0);
setEnglishMarks(value);
}, []);
Putting a value in the dependency array does not work either.
But the following code works. the value
variable retains its value even after refresh
const value = englishResult.reduce((acc, current) => {
acc = parseInt(current.marks);
return acc;
}, 0);
CodePudding user response:
But the following code works. the value variable retains its value even after refresh
const value = englishResult.reduce((acc, current) => { acc = parseInt(current.marks); return acc; }, 0);
That's the code i would recommend anyway for a computed value like this one. Copying it into a different state just makes the component do extra renders and complicates the code.
If the array is particularly large, such that it's causing you a performance issue, you can skip the calculation if nothing has changed by doing useMemo like this:
const value = useMemo(() => {
return englishResult.reduce((acc, current) => {
acc = parseInt(current.marks);
return acc;
}, 0);
}, [englishResult])
Note that you should not set state in useMemo. Just return the value.
CodePudding user response:
You can use localStorage for that: For example: https://www.npmjs.com/package/easy-react-hooks