DEV Community

GaryRoussak
GaryRoussak

Posted on

Best React practice for component which both polls and submits ?

Hi all,

I'm on a project which was coded well before I arrived but I'm wondering if it could better adhere to React principles; I'm looking for recommended general approach here rather than code-level fixes - hope that's OK. I should point out that it's an old React version and some callbacks are deprecated but I can't upgrade right now.

There's a JSX which is responsible for displaying live values from an air-conditioning unit back-end, e.g. a room temperature setpoint, fan speed, on/off mode, louvre direction - that sort of thing.

componentWillReceiveProps() is called; the new props contain all the current values and these are used to set state. As a result, render() is called and live values are now displayed. OK so far ?

The values on the screen are adjustable through various toggle/increment/decrement buttons; the design is such that a change of value isn't sent back instantaneously on a click of those controls but has to be confirmed with a separate SAVE button. Since the values sent to the back-end are now in line with what's displayed (assuming no errors, just to keep things simple in this example), then no further action is required.

However...

I've been asked to add a polling facility to the JS which requests a refresh of the live values every few seconds. I've done this with a simple setInterval(function) approach. Without going into transport details, this causes a fresh callback to componentWillReceiveProps() every ten seconds containing the latest polled values.

It 'works', but there's an issue. Say the current fan speed is MEDIUM. The user decides to change it to HIGH by clicking a 'selector' button but then, for some reason, dawdles and doesn't click SAVE straight away. On screen, the fan speed control has been changed from MEDIUM to HIGH but, all of a sudden, a poll occurs; the existing live value comes back through, the screen re-renders, and the value now returns to MEDIUM before the user has had chance to click the SAVE button. One confused user!

I think the way I would rather this work is as follows. The React detects that the user has changed from MEDIUM to HIGH but knows that SAVE hasn't been clicked yet to confirm submission of the change to the back-end. When the poll occurs and the next props arrive, the logic should detect this value-changed-but-not-yet-submitted condition and NOT set state using the newly polled props -- until, that is, SAVE (or CANCEL) is clicked and this event can be used to reset the condition.

Am I making this too complicated ? Is there a standard way in which React props/state/callbacks should handle this scenario without adding any of my own logic like this ?

Just some pointers please ?

Thanks

Top comments (0)