I am storing a data in a json object. The data is then displayed in a table. But when I refresh the page, all the data is lost. How can I retain the data in the object once it is pushed in the object.
product.json file is an empty json object because I need data to be pushed in it.
<Button
color="success"
type="button"
className="waves-effect waves-light me-1"
onClick={() => {
products.push({
eventID: products.length + 1,
title: this.state.title,
startDate: this.state.startDate,
endDate: this.state.endDate,
time: this.state.time,
address: this.state.address,
link: this.state.URL,
details: this.state.details,
uploadedImage: "Image not available",
});
console.log(products);
this.setState({ addNew: false });
}}
>
Pushing the data in this way. How can I keep the data stored?
You need to store added data somewhere, like server or local storage depends on type of data etc.
You can write JSON into local storage and just use JSON.stringify (non-jQuery) to serialize a JavaScript object. You cannot write to any file using JavaScript alone. Just cookies or local (or session) storage.
const products = [
{
name: 'Dhayalan',
score: 100
}
];
localStorage.setItem('productsStorage', JSON.stringify(products));
And to retrieve the object later, such as on page refresh or browser close/open...
const storedData = JSON.parse(localStorage.getItem('productsStorage'));
We might do something like this also -
<script>
let products = [];
function storeData(data){
products = retriveData();
products.push(data)
localStorage.setItem('productsStorage', JSON.stringify(storedData));
}
function retriveData(){
try{
return JSON.parse(localStorage.getItem('productsStorage'));
} catch(e) {
return [];
}
}
</script>
<Button
color="success"
type="button"
className="waves-effect waves-light me-1"
onClick={() => {
this.storeData({
eventID: products.length + 1,
title: this.state.title,
startDate: this.state.startDate,
endDate: this.state.endDate,
time: this.state.time,
address: this.state.address,
link: this.state.URL,
details: this.state.details,
uploadedImage: "Image not available",
})
console.log(products);
this.setState({ addNew: false });
}}
>