DEV Community

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

Collapse
owenconti profile image
Owen Conti 🇨🇦 • Edited on

Hi Lenmor,

What I would suggest is changing how your store the items in your UI state. For example, instead of storing an array of items, I would store an object, with the keys being the items id property:

setState(_.keyBy(items, 'id'))
Enter fullscreen mode Exit fullscreen mode

Then, I would use your second idea (POST/PUT returns the updated resource). When you go to update the local state after the server responds to the request, you can easily update only the updated item:

setState({
    ...state.items,
    [response.data.id]: response.data
})
Enter fullscreen mode Exit fullscreen mode
Collapse
lennythedev profile image
Lenmor Ld Author • Edited on

Thanks! I was used to having an array before but the idea of using Objects is really growing on me. My app would most likely involve a lot of quick changes in the object's attribute, so this makes a lot of sense.

Collapse
jesseayegba profile image
JesseAyegba

Amazing insight. The only problem I have with storing data in an object is the inability to loop through the items in that object. Using methods like "map" becomes practically impossible for a react developer.

Collapse
owenconti profile image
Owen Conti 🇨🇦

You can get around the loop issue by converting the object to an array before/during render:

Object.values(state.items).map(item => ...)
Enter fullscreen mode Exit fullscreen mode
Collapse
jamesjulius profile image
james-julius • Edited on

How about writing a custom function? I think something like this would work and would create a nice mini-optimisation to use objects as you're suggesting!

function mapObject(obj, callback) {
for (let [idx, val] in obj.entries()) {
callback(val, idx);
}
}