J.S.C
J.S.C

Reputation: 1543

React await async or rerender?

I have a component that renders data received from a server.

I could think of 2 options to use in this case.

  1. trigger fetch function in componentDidMount() and render with initial(empty) data and let redux rerender when the state is set
  2. await in componentDidMount() and wait for servers response, then render with received data

Option1 would load slightly faster with no data then rerender with data (total 2) and Option2 would render only once but component would show slower.

which one is a better approach?

Upvotes: 0

Views: 2652

Answers (1)

keikai
keikai

Reputation: 15146

It depends on what design/demand you have.

One normal approach is to add a loading animation (like material-ui loading) for the request. And only render when the response is reached.

async componentDidMount() {
  await this.request();
}
async request() {
  const req: ReqParamsType = {
    ...
  }
  this.setState({loading: true});
  await this.props.getReports(req);
  this.setState({loading: false});
}
render() {
  const { loading } = this.state;
  return (
    {loading ? <LoadingAnimation /> : <MainContent />}
    ... 

Upvotes: 2

Related Questions