React not rendering properly after an async api fetch

Viewed 39

I have something like this in the code: (this is just an example, so is probably incomplete).

state = {
  showButton: false,
  isLoading: true,
}

async componentDidMount() {
  const { isLoading } = this.state;
  if (isLoading) {
    await this.handleShowButton();
  }
}

handleShowUpload = async () => {
  await apiFetch('GET', { endPoint: 'factory' }).then((factory) => {
    if (factory.data.id === 'MAIN') {
      this.setState({ showButton: true, isLoading: false });
    }
    this.setState({ showButton: false, isLoading: false });
  });
  console.log(showButton, isLoading);
};

render() {
  const { showButton } = this.state;
  render(
    { showButton && (
      <button>Click me</button>
      )
    };
  )
}

The console.log introduced shows properly showButton as true and isLoading as false, but the component seems to render before setState update so the button is not showing. How can I make the button to show up after the apiFetch take place?

0 Answers
Related