Home > front end >  How to get updates from backend automatically in client side
How to get updates from backend automatically in client side

Time:01-13

I have 3 apps, mobile app (react native), web app (react js) and a Nodejs app. the mobile app is an e-commerce mobile app, and the web app is the admin page (client side). The admin page get all data from NodeJs app (api) that use firebase admin sdk.
The problem is that i want everytime a user place an order using the mobile app, the admin page automatically fetch data from NodeJs app.

api code :

router.post("/orders", function(req, res, next) {
  const {filterBy} = req.body;
  let orders = [];
  if(filterBy === "all"){
    db.ref("orders").on('value',function(snap){
      if(snap.val){
        snap.forEach(function(child){
          let items = child.val();
          orders.push(items);
        })
      }
    })
  }else{
    db.ref("orders").orderByChild("generalStatus").equalTo(filterBy)
    .on('value',function(snap){
      if(snap.val){
        snap.forEach(function(child){
          let items = child.val();
          orders.push(items);
        })
      }
    })
  }
  res.json(orders.reverse());
});

CodePudding user response:

You can create a socket connection between your web-app and backend. Whenever someone places an order on the mobile app, you can fire an event in backend api which the client can listen too.

You can use socket.io https://socket.io/get-started/chat

CodePudding user response:

You can also add listener on firebase document and use the method on to check for any changes in DB eg if you want to get updates from chat db you can use this code e.g.

const chatRef = database().ref(firebaseMessages.CHAT);

let listener = chatRef.on('value', snapshot => {
   console.log('User data: ', snapshot.val());
});
//...
// Later when you no longer need the listener
chatRef.off('value', listener);
  • Related