0

I have a button that changes the state of sort to either true or false. This is being passed to the App component from a child using callbacks. The first console log in the refinedApiRequest gives the value of true and then false and then true and so on as the button is click. However, the if statement keeps resulting in the else result regardless of the state of sort (true or false). What is causing this?

I want to assign a variable a value depending on the state of sort so that I can feed this value into the params of a async api get request. Thanks in advance.

class App extends React.Component {
  state = { pictures: '', sort: '' };


  onSortSelect = sort => {
    this.setState({ sort: sort }, () => this.refinedApiRequest(sort));
  }

  async refinedApiRequest(sort) {

    console.log(sort);

    if(sort == 'true') {
      console.log('its true');
    } else {
      console.log('its false');
    }

    const res = await axios.get('url', {
      params: {
        order: {a variable}
      }
    });

    this.setState({ pictures: res.data });

    console.log(this.state.pictures);
  }
BoJack
  • 225
  • 1
  • 2
  • 7

1 Answers1

1

While the optional callback parameter to this.setState is guaranteed to only be executed when the component is re-rendered, in your case it still closes over the sort value of the previous render (ref: How do JavaScript closures work?).

I'd suggest following reacts advice:

The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.

from: https://reactjs.org/docs/react-component.html#setstate

(emphasis by me)

Yoshi
  • 54,081
  • 14
  • 89
  • 103
  • Thank you for the response. Will `componentDidUpdate()` run after onSortSelect runs (and setState is called) without me having to pass it in as a callback? – BoJack Dec 14 '20 at 14:11
  • 1
    @BoJack Check the docs https://reactjs.org/docs/react-component.html#componentdidupdate on how to use it and a better explanation than I could copy here. ;) – Yoshi Dec 14 '20 at 14:13