I have two different components that show different categories of food and trying to implement a save button for both of them using localStorage.
I have this code on both of them
const [menu, setMenu] = useState([]);
const AddtoMenu = (e,selectedItem) => {
let newMenu;
if (menu.includes(selectedItem)) {
// If the item is already in the array, remove it
newMenu = menu.filter(item => item !== selectedItem);
} else {
// If the item is not in the array, add it
newMenu = [...menu, selectedItem];
}
setMenu(newMenu);
}
useEffect(() => {
localStorage.setItem('menu', JSON.stringify(menu));
}, [menu]);
What happens now is that they don’t share the same storage, they replace each other depending on the last item I saved.. how can I make both of them add to the last added item?
>Solution :
Put the state and state setter in a component that’s an ancestor to both, and pass it down to both children.
const [menu, setMenu] = useState([]);
const addToMenu = (e,selectedItem) => {
// ...
};
useEffect(() => {
localStorage.setItem('menu', JSON.stringify(menu));
}, [menu]);
return (
<div>
<Child1 {...{ menu, addToMenu }} />
<Child2 {...{ menu, addToMenu }} />
</div>
);
const Child1 = ({ menu, addToMenu }) => {
// etc
If setMenu is used in the children outside of addToMenu, you can pass that down as well.