Prop is not updating as expected when value is set in a reducer

Viewed 80

I encountered this problem when I was testing my newly created action and reducer. The prop is not being updated even though I'm setting it to a fixed value within my reducer.

Component:

class <ComponentName> extends Component {

    componentDidMount() {
        login()
    }
    
    render() {
        if(this.props.isLogged) 
            return (
                <App/>    
            );
        else 
            return (
                <ErrorScreen/>
            );
    }    
}



function mapStateToProps(state) {
    return {
      isLogged:state.auth.isLogged
    }
}


const mapDispatchToProps = (dispatch) => {
    return {
        login: () => dispatch(login())
    };
};

  
export default connect(mapStateToProps,mapDispatchToProps)(<ComponentName>)

Action:

export function login() {
    return {
        type:"TEST"
    }
}

Reducer:

const initState = {
    isLogged: false,
    
}

export default (state=initState, action) => {
    switch(action.type) {
        case "TEST":
            return {
                ...state,
                isLogged: true
            }
            break;
    default:
        return state     
    }
} 

Combine Reducer:

import {combineReducers} from 'redux'
import AuthenticationReducer from './authenticationReducer'

export default combineReducers({
    auth: AuthenticationReducer
})

Provider:

import React, {Component} from "react";
import <ComponentName> from './app/screens/<ComponentName>'
import store from './app/store'
import {Provider} from 'react-redux'

export default () =>
<Provider store={store}>
  <<ComponentName>/>
</Provider>;

Been trying to debug this for some time now. I still don't know why this is happening. Maybe I implemented it wrongly? If there are some files I forgot to include, please inform me. Thanks and have a nice day!

1 Answers

The reason your code isn't working as expected is because you're calling the login() action creator, rather than the login() method that is returned from mapDispatchToProps() (and injected into the props of <ComponentName/>).

Try revising your code by adding this.props before your call to login() like so:

class <ComponentName> extends Component {

    componentDidMount() {

        // Update this line here so that the login() method 
        // injected by connect() is called (ie via this.props)
        this.props.login()
    }

    render() {
        if(this.props.isLogged) 
            return <App/>
        else 
            return <ErrorScreen/>
    }    
}
Related