Search code examples
javascriptreact-nativereduxreact-redux

State is updating to the component but props is undefined


I just tried to integrate redux into my react-native application.CombineReducer used to combine two reducers but it gives me undefined props.

CounterComponent

 function mapStateToProps(state) {
   console.log(props)  //undefined
   console.log(state); // counterReducer: { counter: 2 }
   return {
       counter: state.counter
   };
  }

reducerIndex.js

import { combineReducers } from 'redux';
import { todoReducer } from './todoReducer';
import { counterReducer } from './counterReducer';
export default combineReducers({
  counterReducer,
  todoReducer
});

App.js

const store = createStore(reducer);

export default class App extends Component {
  render() {
     return (
      <Provider store={store}>
       <CounterApp />
      </Provider>
   );
  } 
}

Solution

  • Yeah thats a valid undefined for the props being accessed in the mapStateToProps because the mapStateToProps is just a normal function that exposes the redux state to your component that you have attached to the store using connect. mapStateToProps doesn't know your component props but it does update them or add more to it by giving your redux state to your component as props thats why it is a good convention to write the function name as mapStateToProps ! so when you write the following:

    class MyContainer extends Component {
       constructor (props) {
          super (props);
       }
       ......
       .....
       render () {
        return <MyCoolComponent />
       }
    };
    
    function mapStateToProps(state) {
      const {myreducer} = state;
      return {
         data: myreducer.data 
      }
    }
    
    function mapDispatchToProps (dispatch, ownProps) {
       return {
          updateData: () => {
             dispatch(someAction());  //someAction: this will return something like this: {type: MY_UPDATE_ACTION}
          }
       }
    }
    
    export default connect(mapStateToProps, mapDispatchToProps)(MyContainer);
    

    So in the MyContainer component, you will have the access to the data as one of its props. You can access data anywhere in the class using this.props.data.

    On the other hand mapDispatchToProps exposes functions as props to the attached component, the functions being exposed have access to the dispatch which actually dispatches an action to the store thereby giving power to your component to mutate the redux store. So with the above explanation, updateData function can be accessed from anywhere in the MyContainer using this.props.updateData().