Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react – add to the same localStorage from two different components

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading