I have a frontend that sends an id automatically when someone visits a URL, like /products/1, /products/2, it send the id like 1 or 2 to the server, then the server send a response for that id back to the browser, now I want to save this response in localStorage, but when someone visits, /1 its saves response in local storage, but now when someone visits, /2 it replaces the previous local storage value instead of adding new, How can I keep on adding new data to localStorage instead of updating the previous value?
fetch("/apps/proxy/sendid", {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(jspid)
}).then(function (response) {
// The API call was successful!
console.log(response);
return response.json();
}).then(function (data) {
// This is the JSON from our response
// This is the JSON from our response
console.log(data);
const productsDetails = [];
productsDetails.push(data);
localStorage.setItem('future', JSON.stringify(productsDetails));
}).catch(function (err) {
// There was an error
console.warn('Something went wrong.', err);
});
}
First, get the current items from localStorage and assigned them to productsDetails. Then append the next items to the array.
let productsDetails = localStorage.getItem('future');
if(null === productsDetails) {
productsDetails = [];
}
productsDetails.push(data);
localStorage.setItem('future', JSON.stringify(productsDetails));