score:3

Accepted answer

The problem here is that setState is async (it can be sync in certain situations). That's why you are get previous value.

There are two possible solutions.

//
// 1. use value directly.
//
switchCategory = (ev) => {
    this.setState({ currentCategory: ev.target.value });
    this.loadData(ev.target.value);
}

loadData = async (currentCategory) => {
    console.log(currentCategory);

    // Get data via XHR...
}

//
// 2. use completition callback on `setState`.
//
switchCategory = (ev) => {
    this.setState({ currentCategory: ev.target.value }, () => {
        this.loadData(ev.target.value);
    });
}

loadData = async () => {
    const { currentCategory } = this.state;
    console.log(currentCategory);

    // Get data via XHR...
}

Article on synchronous setState in React [link]


Related Query

More Query from same tag