I have array in my state I set my state default value to an empty array []
. After an API request loads I need to use loader until data is ready. So U use condition like:
(if array length === 0 loader will show otherwise data will show)
but when the API returns empty data I want to show no data available.
What is best way to do that?
My code is below - how can I check the condition if the API returns an empty result?
this.state.offer.length == 0 ? <Loader /> : <OfferList />
I have array in my state I set my state default value to an empty array []
. After an API request loads I need to use loader until data is ready. So U use condition like:
(if array length === 0 loader will show otherwise data will show)
but when the API returns empty data I want to show no data available.
What is best way to do that?
My code is below - how can I check the condition if the API returns an empty result?
this.state.offer.length == 0 ? <Loader /> : <OfferList />
Share
Improve this question
edited Dec 15, 2017 at 11:08
Brett DeWoody
62.9k31 gold badges144 silver badges192 bronze badges
asked Dec 15, 2017 at 11:03
Narayanan SNarayanan S
1271 gold badge5 silver badges14 bronze badges
2
-
1
When you get the API result you should check if it's length is 0, then have a flag in state and set that like
if responseFromAPI.length==0 this.setState({emptyAPIResponse: true})
, then use that for conditional rendering – Jayce444 Commented Dec 15, 2017 at 11:06 -
Could you provide your
render
function? – Mikhail Katrin Commented Dec 15, 2017 at 11:08
4 Answers
Reset to default 7Easiest would be to have the default be undefined
rather than an empty array. Then in your render check:
undefined
means its loading- empty array means no data, so show message
- non-empty array you can shown data
{!this.state.offer ? <Loader /> : this.state.offer.length ? <OfferList /> : <span>No data available</span>}
Best approach would be to use the ternary operation. First initialize offer to be undefined
and you API returns an empty array if there is no data. Next use below expression in render method().
{this.state.offer === undefined ? <Loader /> : this.state.offer.length > 0 ? <OfferList /> : "No data Available"}
Ideally, you should not show or hide the loader on the basis of the size of your array it should depend on your AJAX call.
Simply you can put a variable in your state like "isLoading", mark it true on making ajax call and mark it false on response independent of whether it is a success or failure.
this.state ={
offer: [],
isLoading: false
}
on ajax, call
this.setState({isLoading:true});
on the response, call
this.setState({isLoading:true});
and you can display
no data available on the basis of size of array.
Add another property in your state
denoting processing like below
state = {
offer: [],
processing: false
}
then use this property to show/hide
your loader.
You can set/unset this property, while you make API call.