5

I am trying to create a container which is subscribed to the store using mapStateToProps. I am able to change the state using reducers in this fashion

export default function firstReducer(state={}, action) {
    switch(action.type){
        case 'ADD_USERNAME':
            return Object.assign({}, state, {
                username: action.payload
            });
        default:
            return state;
    }
}

However, mapStateToProps is not getting called even once. Where am I going wrong

export default class myComponent extends React.Component{
   render(){
       return(
            <h1>this.props.userName</h1>
       )
   }
}

function mapStateToProps(state){
    console.log("Hey");
    return{
        userName: state.username
    };
}

export const myContainer = connect(mapStateToProps, null)(myComponent);
alchemist95
  • 759
  • 2
  • 9
  • 26
  • Are you sure you are using `myContainer ` and not `myComponent`? You should not be exporting both. Especially if you are exporting `myComponent` as your default. – Sulthan Jun 10 '17 at 13:51
  • Minor detail: I think you're supposed to capitalised react component names, so it should be `MyComponent ` instead. – Mμ. Jun 10 '17 at 13:54
  • @Sulthan Is that responsible for mapStateToProps not getting called even once? – alchemist95 Jun 10 '17 at 14:00
  • @D-reaper I have taken care of that. This is just a snippet i wrote for the question – alchemist95 Jun 10 '17 at 14:01
  • @alchemist95 Can you check if 'ADD_USERNAME' action is actually received in the reducer? – Mμ. Jun 10 '17 at 14:02
  • @alchemist95 If you are exporting both that my bet is that you are using `myComponent` and not the container wrapped in `connect`. Show us how are you using that component. – Sulthan Jun 10 '17 at 14:03

1 Answers1

22

Two things that you need to take care of

First have you component name not being with Uppercase letter and second remove the export default from the component, otherwise when you will be importing it as default you wouldn't be using the component that you have connected the store with

class MyComponent extends React.Component{
   render(){
       return(
            <h1>this.props.userName</h1>
       )
   }
}

function mapStateToProps(state){
    console.log("Hey");
    return{
        userName: state.username
    };
}

export default connect(mapStateToProps, null)(MyComponent);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400