I need to render a ponent after data is fetched. If try to load data instantly, ponent 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));
};
ponentDidMount() {
this.getGames();
}
render() {
return (
<div className="App">
<Game gameId={this.state.links[0].id} /> //need to render this part
after data is received.
</div>
);
}
}
I need to render a ponent after data is fetched. If try to load data instantly, ponent 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));
};
ponentDidMount() {
this.getGames();
}
render() {
return (
<div className="App">
<Game gameId={this.state.links[0].id} /> //need to render this part
after data is received.
</div>
);
}
}
Share
Improve this question
edited Jul 27, 2018 at 11:26
Tholle
113k22 gold badges208 silver badges197 bronze badges
asked Jul 27, 2018 at 11:25
EfkissEfkiss
1154 silver badges11 bronze badges
1
- You need to rerender it actually, right? – Abin Thaha Commented Jul 27, 2018 at 11:28
3 Answers
Reset to default 4You 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));
};
ponentDidMount() {
this.getGames();
}
render() {
const { links, isLoading } = this.state;
if (isLoading) {
return null;
}
return (
<div className="App">
<Game gameId={links[0].id} />
</div>
);
}
}
You can do like this using short circuit.
{
this.state.links && <Game gameId={this.state.links[0].id} />
}
Can we use the pattern of "Render-as-you-fetch" to solve the problem. Using a flag to check whether loading is plete doesn't look like a clean solution..