Efkiss
Efkiss

Reputation: 115

React render component asynchronously, after data is fetched

I need to render a component after data is fetched. If try to load data instantly, component gets rendered but no data is show.

class App extends React.Component {
  //typical construct

  getGames = () => {
    fetch(Url, {})
      .then(data => data.json())
      .then(data => {
        this.setState({ links: data });
      })
      .catch(e => console.log(e));
  };

  componentDidMount() {
    this.getGames();
  }

  render() {
    return (
      <div className="App">
        <Game gameId={this.state.links[0].id} /> //need to render this part
        after data is received.
      </div>
    );
  }
}

Upvotes: 2

Views: 9529

Answers (3)

Anish Kelkar
Anish Kelkar

Reputation: 81

Can we use the pattern of "Render-as-you-fetch" to solve the problem. Using a flag to check whether loading is complete doesn't look like a clean solution..

Upvotes: 0

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15290

You can do like this using short circuit.

{
  this.state.links && <Game gameId={this.state.links[0].id} />
}

Upvotes: 1

Tholle
Tholle

Reputation: 112917

You could keep an additional piece of state called e.g. isLoading, and render null until your network request has finished.

Example

class App extends React.Component {
  state = { links: [], isLoading: true };

  getGames = () => {
    fetch(Url, {})
      .then(data => data.json())
      .then(data => {
        this.setState({ links: data, isLoading: false });
      })
      .catch(e => console.log(e));
  };

  componentDidMount() {
    this.getGames();
  }

  render() {
    const { links, isLoading } = this.state;

    if (isLoading) {
      return null;
    }

    return (
      <div className="App">
        <Game gameId={links[0].id} />
      </div>
    );
  }
}

Upvotes: 4

Related Questions