Home > Software engineering >  I want to preserve backend data on reload
I want to preserve backend data on reload

Time:05-03

I have created an app that has a cart that sends data to the backend, now when I restore I want to preserve the data and display the same data as before.

I have used the PUT method instead of POST and when I send and get data from Firebase, data is preserved on reload and the data from the database is visible, but if I use my own backend in Node.js, I am not able to get the data on reload. This is where I am fetching data from the backend.

export const fetchCartData=()=>{
 return async(dispatch)=>{
  const getData= async() =>{
   const response = await fetch('https://localhost:5000/');
   if(!response.ok){
    throw new Error('Something went wrong'); 
   }
   const info=await response.json();
   return info;
};

  try{
   const data= await getData();
   console.log("Here is data from Firebase", data);
   dispatch(order_action.replaceCart({
     items:data.items || [],
     totalQuantity:data.totalQuantity || 0
   }));
  }catch(error){
   dispatch(show_action.showNotification({
     status:"failed",
     title:"Error...",
     message:"Some error occurred."
   }));
  }
 }
}

Tha backend Code is:

const express=require("express");
const bodyParser=require('body-parser');
const cors=require('cors');
const app=express();
app.use(cors());
app.use(bodyParser.json());

app.put("/",function (req,res) {
  const data={
    items:req.body.items,
    totalQuantity:req.body.totalQuantity
  }
console.log(data);
console.log("END");
res.send({data});
})

app.get("/",function (req,res) {
console.log(req.body);
const data={
  items:req.body.items,
  totalQuantity:req.body.totalQuantity
}

res.send({data})
})

app.listen(5000,function () {
console.log("Running on 5000");
})

CodePudding user response:

You can use localStorage on the browser i.e at the client-side. Whenever there is any change in the cart do these steps:

  1. Send data to the backend API using the PUT method and store it in DB or cache(based on the website and users you are dealing with).

  2. Once you get the response from API, update your localStorage data.

localStorage.set('cart', JSON.stringify(dataFromAPI));

Now, on every reload you will always be getting the last updated cart data.

when I send and get data from Firebase, data is preserved on reload and the data from the database is visible

Just for your knowledge, firebase is a database and when you save data, it is persistent. Now, on reload you must be calling the firebase DB to get the data back that's why you see the data on the client otherwise it is impossible to get data without caching or saving it locally.

  • Related