Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement long polling for React + axios

I'm using React + axios to talk to the API from the client side. I'm a newbie in JavaScript.

How would I implement long polling so I get near real-time updates on a web page?

Is there a better way to do real-time updates on the page, when backend is a JSON REST API? Should I look into using WebSockets or server side events or long polling is fine?

like image 639
Maklaus Avatar asked Apr 17 '17 01:04

Maklaus


People also ask

How is long polling implemented?

Long polling is a strategy in which the server chooses to keep a client's connection open for as long as feasible, only responding when data becomes available or a timeout threshold is reached, rather than having to repeat the procedure for each client until new data becomes available.

What is AJAX long polling?

Polling is a standard technique used by the vast majority of AJAX applications. The basic idea is that the client repeatedly polls (or requests) a server for data. The client makes a request and waits for the server to respond with data. If no data is available, an empty response is returned.

Where can I use long polling?

Rather than having to repeat this process multiple times for every client until new data for a given client becomes available, long polling is a technique where the server elects to hold a client's connection open for as long as possible, delivering a response only after data becomes available or a timeout threshold ...


1 Answers

There is another, potentially better way for your use-case: Server-Sent Events.

SSE, in a nutshell, is a simple GET request to the server from the client - except that the server doesn't close the connection after it's done processing the request. Instead, the HTTP connection is left open and the server is able to write data multiple times to the client, which appear in real-time.

For more info on how SSE compares to Websockets, read Alex Recarey's answer to "WebSockets vs. Server-Sent events/EventSource" in SO.

like image 171
Alfonso Gober Avatar answered Sep 20 '22 15:09

Alfonso Gober