What is the standard way to keep UI state and backend state synced during updates? (React and Node)

Lenmor Ld - May 9 '19 - - Dev Community

Let's say i have a Node-Express backend with a REST API and a React frontend that has some editable Card. On App load, I fetch an items array and do a setState

componentDidMount() {
    axios.get('/items').then(() => {
        this.setState({ items: res.data })  // res.data is array of items
    })
}

When user updates the card, I send a PUT or POST request to the backend,
which updates the card details (with or without DB doesnt matter, just assume backend state is updated). good.

My question is, what's the best way to update the UI ?
Is there a standard way when doing REST?

Here are the ideas I could come up with:

  • On my server PUT/POST route handler, i could return items array, including the one updated. On UI, I could then do a simple setState({ items: res.data }). Returning the entire items array seems expensive though, considering only one item is updated.

    • At least backend is source of truth, if update fails, i could easily tell UI error happened.
  • On my server Put/POST route handler, i could return only updated item.
    I would then have to find and replace the updated item in my state and do a setState({ items: res.data })

    • Simple enough, but it feels like i'm doing extra work. But since my data structure is an array, I have to replace entire array in UI state.
    • Or is there a better way to update only one item in an array in state, or maybe better to change my data structure to an object, so setState is optimal.
  • On my server Put/POST route handler, i could return a status code/message to signal UI that operation succeeded and now I can update UI state.

  • On UI side, I do the update first, then send the updates to backend.

    For some reason if it fails in backend, then I rollback UI changes (might be tricky?)

  • Use localStorage in between?

any other ideas?

This is probably handled better in GraphQL and using state management like Flux,
but if i'm doing it really vanilla Node and React, what's the best way?

Let me know if my question isn't clear enough, i could elaborate

Thanks!

. . . . . . . . . . . . . . . .
Terabox Video Player