Search code examples
reactjsreduxreact-reduxreact-on-rails

Redux Reducer that simply returns an action's value and not a state?


I have a Container, an actionsCreator, and a reducer. In the below code, what's enabling the Reducer to return action.text instead of an updated state object? I thought reducers had to always return states.

HelloWorldContainer.jsx

 import { connect } from 'react-redux';
 import HelloWorld from '../components/HelloWorld';
 import * as actionCreators from '../actions/helloWorldActionCreators';

 const mapStateToProps = (state) => ({ name: state.name });

 export default connect(mapStateToProps, actionCreators)(HelloWorld);

helloWorldActionCreators.jsx

 import { HELLO_WORLD_NAME_UPDATE } from '../constants/helloWorldConstants';

 export const updateName = (text) => ({   
   type: HELLO_WORLD_NAME_UPDATE,  
   text, 
 });

helloWorldReducer.jsx

 import { combineReducers } from 'redux';
 import { HELLO_WORLD_NAME_UPDATE } from '../constants/helloWorldConstants';

 const name = (state = '', action) => {
   switch (action.type) {
     case HELLO_WORLD_NAME_UPDATE:
       return action.text
     default:
       return state;
   }
 };

 const mainReducer = combineReducers({ name });

 export default mainReducer;

(Code source: React on Rails).


Solution

  • The name is just a slice of state. And action.text is the updated state.

    After combineReducers({ name }), the state tree looks like:

    {
      name: '..'
    }
    

    Besides, redux doesn't limit you that you can only use object as your state. If you pass name to createStore() directly without combineReducers, your entire state will become a plain string.