DEV Community

How to store relational data inside Redux

Francesco Pigozzi on April 03, 2019

Photo by Tobias Fischer on Unsplash Sooner or later, all frontend developers need to save relational data in a Redux store. TL;DR Fo...
Collapse
 
amitneuhaus profile image
Amit Neuhaus

Hey, great post!
Question about changing data in this kind of structure like adding/deleting children of a parent:
If I want to add a new comment , the comments reducer will add the comment object and the new comment ID to the relevant sections on the comments state, but what about the post state?
Something has to update the comments array in the relevant post state with the new comment ID.
if for example I render a table of posts with comments id's column, the new comment wont show.

Should I access the comments state and for each post row map to see which comments have this post id as parent
Or
Should I just add the comment ID to the comments array in the post state on creation so I won't even need to access the comments state when rendering the posts table?

how would you structure it?

Collapse
 
shushpan profile image
Pavel Shushpan

Hey!
Did you see this library? it makes it easy to structure your store
also, it's described in redux docs

Collapse
 
pigozzifr profile image
Francesco Pigozzi

Hey Pavel!

Yes, I knew that library. However, it seems that its purpose is to, actually, normalize some nested data coming from some kind of source.

It could be a step before saving some data inside the kind of structure I described here. What do you think?

Collapse
 
lineldcosta profile image
lineldcosta

Yes perfect! i do use the same approach.

Collapse
 
desirepeeper profile image
Ali Almohsen

This structure feels much cleaner to me: gist.github.com/AliRain/606ac00d05...

Collapse
 
pigozzifr profile image
Francesco Pigozzi

This structure feels much more like a relational set of records to me too. But how would you access a single record without looping through the whole array? This sounds like a performance pitfall.