Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  36] [ 4]  / answers: 1 / hits: 41904  / 8 Years ago, fri, april 22, 2016, 12:00:00

Is it possible to combine reducers that are nested with the following structure:



import 'user' from ...
import 'organisation' from ...
import 'auth' from ...
// ...

export default combineReducers({
auth: {
combineReducers({
user,
organisation,
}),
auth,
},
posts,
pages,
widgets,
// .. more state here
});


Where the state has the structure:



{
auth: {
user: {
firstName: 'Foo',
lastName: 'bar',
}
organisation: {
name: 'Foo Bar Co.'
phone: '1800-123-123',
},
token: 123123123,
cypher: '256',
someKey: 123,
}
}


Where the auth reducer has the structure:



{
token: 123123123,
cypher: '256',
someKey: 123,
}


so maybe the spread operator is handy? ...auth not sure :-(


More From » reactjs

 Answers
24

It is perfectly fine to combine your nested reducers using combineReducers. But there is another pattern which is really handy: nested reducers.



const initialState = {
user: null,
organisation: null,
token: null,
cypher: null,
someKey: null,
}

function authReducer(state = initialState, action) {
switch (action.type) {
case SET_ORGANISATION:
return {...state, organisation: organisationReducer(state.organisation, action)}

case SET_USER:
return {...state, user: userReducer(state.user, action)}

case SET_TOKEN:
return {...state, token: action.token}

default:
return state
}
}


In the above example, the authReducer can forward the action to organisationReducer and userReducer to update some part of its state.


[#62441] Wednesday, April 20, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gideons

Total Points: 197
Total Questions: 106
Total Answers: 108

Location: Moldova
Member since Sat, Jan 29, 2022
2 Years ago
gideons questions
Tue, Nov 9, 21, 00:00, 3 Years ago
Sat, Jan 2, 21, 00:00, 3 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Thu, May 21, 20, 00:00, 4 Years ago
;