https://grokonez.com/frontend/redux/redux-combinereducers-example

Redux combineReducers example

From Redux Introduction, we know that there is only a single Store in a Redux application. When we want to split data-handling logic, we will combine Reducers instead of using many Stores. This tutorial shows you way to use Redux combineReducers() function in a Redux example.

Full example with filtering and sorting: Redux Reducer example - filter & sort data

Overview

combineReducers

If we have state whose values seem to correspond to different reducing functions like this:

const demoState = {
    books: [
        {
            id: '123abcdefghiklmn',
            title: 'Origin',
            description: 'Origin thrusts Robert Langdon into ...',
            author: 'Dan Brown',
            published: 2017
        },
        {
            ...
        }
    ],
    filters: {
        text: 'ori',
        sortBy: 'published',
        startYear: undefined,
        endYear: undefined
    }
};
We won't use only one Reducer to handle Action logic but two Reducers: one for books, and one for filters. Now, combineReducers() comes to be the solution. It combines 2 reducing functions into a single reducing function that can be passed to createStore():

const rootReducer = combineReducers({
    books: booksReducer,
    filters: filtersReducer
})

const store = createStore(rootReducer);

combineReducers rules

The Reducer that is passed to combineReducers() function must satisfy these rules: - For unrecognized Action: return the given state as the first argument. (we usually return state in default case of switch statement) - Never return undefined. - If the given state is undefined: return the initial state. So the initial state must not be undefined either.

Example Description

We will create a Redux Application that has: - state that contains 2 components: books array and filters. - 3 types of Actions: + 'ADD_BOOK', 'REMOVE_BOOK' for books. + 'FILTER_TEXT' for filters. - 2 child Reducers (booksReducer and filtersReducer) that will be combined using combineReducers() function.

We can add/remove books to/from books, set filters.text value.

Practice

Setup environment

In package.json:

More at:

https://grokonez.com/frontend/redux/redux-combinereducers-example

Redux combineReducers example

#redux #combinereducers

Redux combineReducers example » grokonez
2.85 GEEK