Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch data on Async ComponentDidMount before rendering

Tags:

reactjs

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)
}
like image 920
David Avatar asked Jan 28 '23 13:01

David


2 Answers

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.

like image 31
Jim Wharton Avatar answered Feb 15 '23 18:02

Jim Wharton


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.

like image 97
jens Avatar answered Feb 15 '23 18:02

jens