Hey guys, got a custom localstorage hook, but I need to store it as an object of boolean values for list items. Basically storing a favorite state on each item and set that value to local storage. How can this be done? Currently I can toggle the state back and forth on each item, but currently it only saves that one value and when I reload the page they are all favorited.
Here is the hook:
import { useState, useEffect } from 'react';
const useLocalStorage = (key, defaultValue) => {
const [value, setValue] = useState(() => {
let val;
try {
val = JSON.parse(window.localStorage.getItem(key) || String(defaultValue));
} catch (e) {
val = defaultValue
}
});
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [value]);
return [value, setValue];
}
export { useLocalStorage };
And how I am using it in the list item component:
const [favorite, setFavorite] = useLocalStorage('favorite', false);
const handleToggle = () => {
setFavorite(!favorite);
};