0

I want to make a progress bar kind of telling where the user where in process of fetching the API my backend is. But it seems like every time I send a response it stops the request, how can I avoid this and what should I google to learn more since I didn't find anything online.

React:

const {data, error, isError, isLoading } = useQuery('posts', fetchPosts) 
if(isLoading){<p>Loadinng..</p>}
return({data&&<p>{data}</p>})

Express:

app.get("api/v1/testData", async (req, res) => {
    try {
        const info = req.query.info
        const sortByThis = req.query.sortBy;
        if (info) {
            let yourMessage = "Getting Data";
            res.status(200).send(yourMessage);
            const valueArray = await fetchData(info);
            yourMessage = "Data retrived, now sorting";
            res.status(200).send(yourMessage);
            const sortedArray = valueArray.filter((item) => item.value === sortByThis);
            yourMessage = "Sorting Done now creating geojson";
            res.status(200).send(yourMessage);
            createGeoJson(sortedArray)
            res.status(200).send(geojson);
        }
        else { res.status(400) }
    } catch (err) { console.log(err) res.status(500).send }
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ole Dybedokken
  • 343
  • 2
  • 15

1 Answers1

1

You can only send one response to a request in HTTP.

In case you want to have status updates using HTTP, the client needs to poll the server i.e. request status updates from the server. Keep in mind though that every request needs to be processed on the server side and will take resources away which are then not available for other (more important) requests from other clients. So don't poll too frequently.

If you want to support long running operations using HTTP have a look at the following API design pattern.

Alternatively you could also use a WebSockets connection to push updates from the server to the client. I assume your computation on the backend will not be minutes long and you want to update the client in real-time, so probably WebSockets will be the best option for you. A WebSocket connection has, once established, considerably less overhead than sending huge HTTP requests/ responses between client and server.

Have a look at this thread which dicusses abovementioned and other possibilites.

Mushroomator
  • 6,516
  • 1
  • 10
  • 27