Phil
Phil

Reputation: 1662

React/Redux wait for store to update

I am currently building my first app using react and redux. I have built some filters and when the user selects a filter, it will update the store with the new filter value, and then request the new results.

The store is being updated with the new filter value, but the fetch request is happening before the store has finished updating and so returns the incorrect value.

How can i wait for the store to update before making the fetch request?

Below is my code...

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

class Filters extends Component {
constructor(props){
    super(props);
    this.handleChange = this.handleChange.bind(this);
}

handleChange(value, dispatcher){
    dispatcher(value.props["data-attr"]);

    this.props.resultsFetchData('/api/deals/?data=' + this.props.dataFilter);
}

render() {
    const dataFilters = {
        0: <span data-attr="0">Any</span>,
        20: <span data-attr="1">1GB+</span>,
        40: <span data-attr="2">2GB+</span>,
        60: <span data-attr="5">5GB+</span>,
        80: <span data-attr="10">10GB+</span>,
        100: <span data-attr="99.99">Unltd</span>
    };

    return (
        <div className="filters">
            <div className="row">
                <div className="col-sm-4 filters--slider">
                    <Slider
                        min={0}
                        marks={dataFilters}
                        step={null}
                        defaultValue={this.props.dataFilter}
                        onChange={e => {this.handleChange(dataFilters[e], this.props.setDataFilter)}} />
                </div>
            </div>
        </div>
        );
    }
}

export default connect(mapStateToProps, {setDataFilter, resultsFetchData})(Filters)

Filters.propTypes = {
dataFilter: PropTypes.string
}

Upvotes: 3

Views: 1663

Answers (1)

Phil
Phil

Reputation: 1662

Using componentWillReceiveProps worked as a solution for me...

componentWillReceiveProps(nextProps){
    if(nextProps.dataFilter !== this.props.dataFilter){
        this.props.resultsFetchData('/api/deals/?data=' + nextProps.dataFilter);
    }
}

handleChange(value, dispatcher){
    dispatcher(value.props["data-attr"]);
}

Upvotes: 1

Related Questions