react-redux current props value

274 views Asked by At

I've three buttons on the page, and when clicking on any button i want to get that selected value from the store filtered by id(done in reducer). I'm trying to use redux with mapStateToProps and mapDispatchToProps pattern, but looks like when i try to access the current selected value from the store after clicking on any button, it doesn't reflect the correct value in the console. Is this not how "this.props.anyPropValue" be used? Can you help clarify what's wrong in my example? First time it prints default value when clicking any button, clicking again prints the previously clicked button value not the current one.

Here is a sandbox link to the simple app i created for the above

sandbox link of the code

1

There are 1 answers

7
Kalhan.Toress On

Most of the code that you have wrote is correct, If you are expecting to see the updated output right after calling the action, it won't work

onGetCountryById(id) {
    this.props.fetchCountryById(id);
    console.log(this.props.country); // This will gives you the current country (We just update the state, but still that value didn't update the component)
}

try to print the value of the country in the html as below and you will see it's getting updated

{this.props.country === null ? "default" : this.props.country.name}

in the reducer you might need to do this change

case CountryActions.FETCH_COUNTRY_BY_ID:
    return {
        ...state,
        country: state.countries.find((item) => item.id === action.id) // use find instead of filter
    };

and set the initial value of the country set to null

const initCountriesState = {
    country: null,
    countries: [
        ....
    ]
};

here is the updated sandbox