How can I add elements to arrays without overwriting them?

Issue

This Content is from Stack Overflow. Question asked by Chris_Len

I have an issue with saving items into an array in JavaScript (or Next.js). At the beginning I have an empty array. Then a session is started, and I check if the session is empty or not. If it is empty, I write a response of a get-request into a variable. At the same time I also write the response of the get request into the local storage.
Basically I now want to write the value of the local storage into the array with the push-method.
In the next step my program should realize, that the session is not empty anymore and now the new value of the get-request should be stored into the local storage and at the same time it should be added as a new element of the variable. The old elements of the array should not be overwritten. I have now tried a couple of things, but I could not get it to work.

Does anybody have a hint for me, how to realize this problem? I would be very thankful, if anybody could help me on this one 😊

api.get(
  'products?include=' + mainId,
  addOrViewCartConfig // a config which is not important for the question
)
.then((response) => {
  // Successful request
  console.log('yes, it worked');
  console.log('response', response);

  if (isEmpty(storedSession)) {
    storeSession(
      response.data[0].id
    );
    localStorage.setItem('ID', response.data[0].id);
    var localCart = [];
    console.log('response2', response.data[0].id);
    console.log('session', storedSession);
    console.log('localCart1', localCart);
    // return localCart;
  }
  console.log('localCart2', localCart);
  console.log('session1', storedSession);

  if (!localCart.indexOf(parseInt(localStorage.getItem('ID')))) {
    localCart.push(parseInt(localStorage.getItem('ID')));
  } else {
    alert('The item you are trying to add is already in your cart!');
    return false;
  }
  console.log('localCart3', localCart);

  viewCart();
})
.catch((error) => {
  console.log('apiError');
  //Invalid request, for 4xx and 5xx statuses
});



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?