Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composing reducers with nested array

Tags:

redux

reducers

I'm using Redux for a while now and I'm loving it :)

I'm a bit confused on how to compose reducers when dealing with nested arrays. I've a user object, which has a list of reviews. Each review can have a list of review_comments.

{
  user: {
  id: 1, 
  reviews: [{
     id: 1, 
     comments: [{
        id: 1, 
        message: "Test"
     }, {
        id: 2, 
        message: "123"
     }, {
        id: 3, 
        message: "456"
     }]}, {
        id: 2, 
        comments: [{
            id: 5, 
            message: "qwerty"
        }, {
            id: 6, 
            message: "1542354"
        }, {
            id: 7, 
            message: "45we 6"
        }]
    }]
}}

Now, all these are in the same UserReducer. I'm mapping through the list of reviews/ comments every time there is a state change. As the size of my data grows, the reducers become more nested and complex to manage.

Is there a way to compose this into 3 reducers: UserReducer, ReviewReducer and CommentReducer?

Thanks for the help.

like image 764
skmvasu Avatar asked Sep 26 '22 17:09

skmvasu


1 Answers

Absolutely. It is much easier to work with flat structure.

Take a look on https://github.com/gaearon/normalizr for ideas about splitting the data. And on https://github.com/rackt/reselect for preparing state data to be used in your components.

Idea is to split entity data on several reducers by entity type. Then build a selector - function that takes global store and return some data structure convenient for you.

like image 150
Vladimir Danchenkov Avatar answered Oct 18 '22 04:10

Vladimir Danchenkov