skip to Main Content

I’m Using React js requesting from the server to get an array of data and updates for each change in the collection, node js, and express is the server side and I’m using Admin SDK to fetch the data from Firebase, Here is the code.

useEffect(()=>{
    const fetchData = async () =>{

            const res = await axios.post('http://localhost:3001/api/orders/order', 
            body,{
                  headers:{
                    "Content-Type":"application/json",
                    Authorization: 'Bearer' + token
                  }
                })
                    
                setData(res.data.list)
                
            }
      
    fetchData()
  },[])

Then in express server Node Js this is how I send the response

app.post('/api/orders/order', async(req, res)=>{

    const ordersDoc = admin.firestore().collection('Orders')

    await ordersDoc.onSnapshot((doc)=>{
        doc.docChanges().forEach(document => {
        if (document.type === 'added') {
            list = []
            list.push({id: document.doc.id, ...document.doc.data()})
            return res.send({list: list})
         }
       if (document.type === 'removed') {
           list = []
           list.push({id: document.doc.id, ...document.doc.data()})
           return res.send({list: list})
         }
      })
        
    })

In express, you can’t send more than one response to the client for sane request.

So the question is how to send a response whenever new data is added to Firestore in real-time and send the data back to clint?

I have tried res.wright() but it only send a string and I want to send an array of object + I didn’t receive any response in react web app.

2

Answers


  1. The easiest way is probably to first build up the response over all documents, and then send it back at the end of the loop. Something like:

    app.post('/api/orders/order', async(req, res)=>{
        const ordersCollection = admin.firestore().collection('Orders');
    
        const querySnapshot = await ordersCollection.get();
      
        const response = querySnapshot.docChanges().map((change) => {
            if (change.type === 'added') {
                return { id: change.doc.id, ...change.doc.data() };
            }
            if (change.type === 'removed') {
                return { id: change.doc.id, ...change.doc.data() };
            }
        })
        return res.send(response);
    })
    
    Login or Signup to reply.
  2. My suggestion would be to use either server-side events(SSE) or sockets. Either way, you need to maintain a secure connection between the server and the client so that the server can send updates based on any activity in the database using the snapshot feature.

    Note: Using web sockets is the standard for having near real-time communication between the services but also depends on your exact use case.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search