I have an issue with saving items into an array in JavaScript/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 localstorage.
Basically I now want to write the value of localstorage 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 localstorage 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).then((response) => {
if (isEmpty(storedSession)) {
storeSession(response.data[0].id);
localStorage.setItem('ID', response.data[0].id);
var localCart = [];
};
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;
}
viewCart();
}).catch((error) => {
console.log('apiError');
});