Skip to content
Advertisement

Size of object array is being added to the localstorage not the array of objects

  useEffect(() => {
    const arr = {
      i: id,
      quant: quantity,
    };
    if (localStorage.hasOwnProperty('quantityData') === true) {**checking if the local storage has the 'quantityData' property already**
      if (JSON.parse(localStorage.getItem('quantityData').length !== 0)) {
        const getData = JSON.parse(localStorage.getItem('quantityData'));
        console.log(getData);
        const val = getData.find(x => x.i === id);**checking if array has the object with particular id property**
        if (val) {**if yes then I will update the quant property of that object with current quantity(state variable)**
          getData.forEach(x => {
            if (x.i === id) {
              x.quant = quantity;
              localStorage.setItem('quantityData', JSON.stringify(getData));
            }
          });
        } else {
          localStorage.setItem(
            'quantityData',
            JSON.stringify(getData.push(arr))**If I dont find the element then I will just push the new element in the quantity Data array
          );
        }
      }
    } else {
      const a = [];
      a.push(arr);
      localStorage.setItem('quantityData', JSON.stringify(a));**Here when I am uploading the array to the local storage I am getting the size of array in the local storage instaed of the object array**
    }
  }, [quantity]);

When I am Uploading the data to the localStorage I am getting the size of object array that I have created instead of the array with data object

Advertisement

Answer

Javascript array function push returns the new length of the array. You need to push and setItem like belows.

getData.push(arr)
localStorage.setItem(
    'quantityData',
    JSON.stringify(getData)
);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement