I\'m learning react and it\'s great, but i\'ve ran into an issue and i\'m not sure what the best practice is to solve it.
I\'m fetching data from an API in my compon
It Depends. suppose you are fetching books data from server. here is how to do that.
state = {
books: null,
}
if, your backend api is correctly setup. You will get either empty array for no books or array with some length
componentDidMount(){
getBooksFromServer().then(res => {
this.setState({
books: res.data
})
})
}
Now In Your render method
render() {
const { books } = this.state;
let renderData;
if(!books) {
renderData =
} else
if(books.length === 0) {
renderData =
}
else {
renderData =
}
return renderData;
}
If you are using offline data persistence In that case initally you won't have emoty array.So This way of handling won't work. To show the spinner you have to keep a variable loader in state. and set it true before calling api and make it false when promise resolves or rejects.
finally read upon to state.
const {loader} = this.state;
if(loader) {
renderData =
}