4

In my componentWillMount function, I have an async function getResults that fetches data from a server. I want to pass the response from getResults to the same component on initial load, but I noticed that my component renders before waiting for the data to come back from getResults. How do I make the component wait for the response before having it render? I am using Redux to handle my state.

async componentWillMount() {
    const response = await getResults(this.props.category)
}
4
  • Possible duplicate of How to wait for AJAX response and only after that render the component? Commented Mar 4, 2018 at 21:59
  • I want to render state before the component mounts; not after. Commented Mar 4, 2018 at 22:09
  • 1
    You cannot force the component's render method to wait for your asynchronous request but you can do a conditional render. Read the accepted answer's last part please. Commented Mar 4, 2018 at 22:14
  • I was trying to see if there was a around that. Looks like there isn't. Thanks! Commented Mar 4, 2018 at 22:17

3 Answers 3

5

Async/Await only makes your code look synchronous.

async componentWillMount() {
  const response = await getResults(this.props.category)
  this.setState({
    // use response to set your state.
  });
}

Set state is what causes the re-render.

You then use the state to determine if you are in a loading state. If so it may be good to show the user. You also want to handle the default data in the first render. Once you retrieve your response you set the data to the second state.

Sign up to request clarification or add additional context in comments.

Comments

2

It's idiomatic React to render your component asynchronously. You'll fetch your data, and set your state accordingly... with a new state, your component will re-render. A common practice it to render the component with a spinner, and when the state is set, re-render with the actual data. At the very least, you can render null until your async request completes and sets your state.

Comments

1

componentWillMount() is invoked just before mounting occurs. It is called before render(), therefore calling setState() synchronously in this method will not trigger an extra rendering. Generally, we recommend using the constructor() instead.

Avoid introducing any side-effects or subscriptions in this method. For those use cases, use componentDidMount() instead.

This is the only lifecycle hook called on server rendering.

source

You can use componentDidMount() and make the rendering conditional and waiting for the result from the API, and then render it with the result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.