Michail  Pidgorodetskiy
Michail Pidgorodetskiy

Reputation: 117

Nesting/combining combined reducers in redux?

How to combine combined reducers for example like this?:

export const streamsRootReducer = combineReducers({
    streamsPending: streamsPendingReducer,
    streams: streamsReducer,
    streamsError: streamsErrorReducer,
    streamsPageOffset: streamsPageOffsetReducer,
    streamsRefresh: streamsRefreshReducer
}); 

export const newsRootReducer = combineReducers({
    newsPending: newsPendingReducer,
    news: newsReducer,
    newsError: newsErrorReducer,
    newsRefresh: newsRefreshReducer
})

export const rootReducer = combineReducers({
    streamsRootReducer: streamsRootReducer,
    newsRootReducer: newsRootReducer
})

export type StreamsRootState = ReturnType<typeof streamsRootReducer>;
export type NewsRootState = ReturnType<typeof newsRootReducer>;

and in the Store like this:

import { rootReducer } from '../reducers/index';


const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware, reduxLogger];

const configureStore = () => {
    const store = createStore(
        rootReducer,
        compose(applyMiddleware(...middlewares))
    );
    sagaMiddleware.run(rootSaga);
    return store;
}

export default configureStore;

and in my screens i want to do like this:

...
const mapStateToProps = (state: NewsRootState) => ({
    newsPending: state.newsPending,
    news: state.news,
    newsError: state.newsError,
    newsRefresh: state.newsRefresh
})

export default connect(
    mapStateToProps,
    { fetchNewsPending, fetchNewsRefresh }
)(NewsScreen)

i am getting errors if i am trying to combine already combined reducers but nesting all my reducers in one combined looks like a mess becasue i want to do similar to this 2 combined in the end of my project i will maybe have like 15 - 20 reducers, should i put all of the in to one rootReducer or can i nest them somehow like in my example? Is there exist better solution to do something like i wanted ?

Upvotes: 0

Views: 180

Answers (1)

Danoz
Danoz

Reputation: 1087

By the looks of it, in your example when you eventually use

export const rootReducer = 
combineReducers({
    streamsRootReducer: streamsRootReducer,
    newsRootReducer: newsRootReducer
})

... it actually just combines all reducers together anyway.

So, I'm thinking that there is no need for a multi-stage combine. You could simply achieve the same result with something like the following:

// imports here... then...

export const rootReducer = combineReducers({
    streamsPending: streamsPendingReducer,
    streams: streamsReducer,
    streamsError: streamsErrorReducer,
    streamsPageOffset: streamsPageOffsetReducer,
    streamsRefresh: streamsRefreshReducer,
    newsPending: newsPendingReducer,
    news: newsReducer,
    newsError: newsErrorReducer,
    newsRefresh: newsRefreshReducer
})

export type RootState = ReturnType<typeof rootReducer>

Would this work?

Upvotes: 1

Related Questions