skip to Main Content

just have a question about how to push onto an array to ultimately store in the localstorage. I have the below code:

  const handleSelectLayouts = (layout) => {
    const layoutsArray = [];
    layoutsArray.includes(layout)
        ? layoutsArray.filter((str) => str !== layout)
        : layoutsArray.push(layout);
    localStorage.setItem('layouts', JSON.stringify([...layoutsArray]));
    console.log(layoutsArray)
  }

I see it in localstorage, however, it only has one item at a time. In the code, I am trying to push onto an array. Not just have whatever is the most recent item inside the array alone. Anyone see anything odd here?

2

Answers


  1. You need to retrieve the previously stored layoutsArray from the local storage

     const handleSelectLayouts = (layout) => {
          let layoutsArray = JSON.parse(localStorage.getItem('layouts')) || [];
          if (layoutsArray.includes(layout)) {
            layoutsArray = layoutsArray.filter((str) => str !== layout);
          } else {
            layoutsArray.push(layout);
          }
          localStorage.setItem('layouts', JSON.stringify(layoutsArray));
          console.log(layoutsArray)
        };
    
    Login or Signup to reply.
  2. You are defining a new layoutsArray every time the function is called

    const layoutsArray = [];
    

    If you want to add to the array which is already in localStorage then try this

    const layoutsArray = JSON.parse(localStorage.getItem('layouts')) || [];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search