Answer the question
In order to leave comments, you need to log in
How to load data before rendering in React?
Hello, is there any way to load data from the Rest API before the render is executed, I tried to do it using componentDidMount, but the data is loaded a little later, i.e. the page is empty for a few seconds after loading, how can I deal with this problem?
Answer the question
In order to leave comments, you need to log in
`componentDidMount` fires after `render`, you can show preloader while data is loading, show data after loading
class example extends React.Component {
state = {
data: [],
isLoading: true,
}
componentDidMount() {
fetch('example/url')
.then(response => response.json())
.then(data => this.setState({ data }))
}
render() {
const { isLoading } = this.state
if (isLoading) {
return <div>Загрузка</div>
}
return data.map(item => <div key={item.id}>{item.name}</div>)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question