Where does the root reducer come from in this redux react example and how does dispatch knows which reducer to go?

Viewed 774

Trying to go through redux react tutorial and I am wondering where rootReducer come from

import { createStore } from "redux";
import rootReducer from "./reducers";

export default createStore(rootReducer);

Does combineReducers auto export rootReducer?

https://codesandbox.io/s/9on71rvnyo?file=/src/redux/store.js

Second question in

/components/AddTodo.js

handleAddTodo = () => {
  this.props.addTodo(this.state.input);
  this.setState({ input: "" });
};

handleAddTodo calls the addTodo action

/redux/actions.js

export const addTodo = content => ({
  type: ADD_TODO,
  payload: {
    id: ++nextTodoId,
    content
  }
});

Which just returns an object

But what connects the addTodo to the reducer itself in /reducers/todos.js?

export default function(state = initialState, action) {

  switch (action.type) {
    case ADD_TODO: {

      .....
2 Answers

Does combineReducers auto export rootReducer?

Yes it does

export default combineReducers({ todos, visibilityFilter });

is enough

What connects the addTodo to the reducer itself in /reducers/todos.js?

The dispatch function, when you call this:

this.props.addTodo(this.state.input);

under the hood you're actually running something like this:

dispatch(addTodo(this.state.input))

This is the pseudo code for combineReducers:

function combineReducers({ reducer1, reducer2 }) {
  return (state, action) => {
    if (action.type === 'reducer1') return reducer1(state.reducer1, action);
    if (action.type === 'reducer2') return reducer2(state.reducer2, action);
  }
}

It's not entirely correct, esp. the returning part, but hopefully it gives you an idea.

Basically, what it does is to create one big reducer that works as if both reducers are combined into one. A reducer is, as you may already know, one function that accepts the previous state and the action, and returns the next state.

Second question: connect does the trick. Once you connect your addTodo prop to the store, the store which already is connected to the reducer, will call the reducer (again, ONE BIG function) with the (prevState, action) value. action will be the return value of addTodo action generator method.

And the reducer does the rest, i.e. checks if the matching action type (in this case, ADD_TODO) exists and does what it does.

Related