2

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>
    );
  }
}
1
  • You need to rerender it actually, right? Commented Jul 27, 2018 at 11:28

3 Answers 3

4

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>
    );
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your help! as soon as I reach 15 reputation points I will upvote your answer :). Might be today.
Would that still be a good option today if data is needed before render, also what if we do not need data state but rather ref instead, how do we trigger re render
1

You can do like this using short circuit.

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

1 Comment

even though I've tried it earlier, your example does work. thank you!
0

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..

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.