I’m trying to do loading spinner using ActivityIndicator with ReactNative. I’ve mocked rest api to see if spinner works. The problem is, despite that I am using ActivityIndicator, I see component which I have not created, while isLoading is true.
Component I see instead has text ‘Loading…’ in top left corner.
loading component
Function which mocks endpoint with loading time:
async fetchFishDetails(fishId: number): Promise<ApiResponse<any>> {
let fish: Fish | undefined
let user: any | undefined
fish = this.user1.fishes.find(fish => fish.id === fishId)
user = this.user1
if (fish === undefined) {
fish = this.user2.fishes.find(fish => fish.id === fishId);
user = this.user2
}
await new Promise(resolve => setTimeout(resolve, 1000))
return {
status: 200,
body: {fishDetails: fish, user: user}
}
}
Function that handle response from function above:
export const getFishDetails = async (fishId: number): Promise<ServiceResponse<any>> => {
console.debug('getFishDetails(), fishId=', fishId);
try {
const response = await fishRestApi.fetchFishDetails(fishId);
if (response.status === 200) {
return new ServiceResponse(Type.SUCCESS, response.body);
} else {
console.error('Error occurred fetching fish from backend')
return new ServiceResponse(Type.FAIL, undefined);
}
} catch (error) {
console.error('Error occurred getting fish, err=', error);
return new ServiceResponse(Type.FAIL, undefined);
}
};
Fetching data in component
useEffect(() => {
setIsLoading(true)
console.log('start loading')
getFishDetails(fishId)
.then(response => {
if (response.type === Type.SUCCESS) {
const {fishDetails, user} = response.body;
setFishDetails(fishDetails);
setUser(user);
setProfilePictureUri(user.picture ? {uri: user.picture} : require('../assets/user-default.png'));
} else {
console.log('Failed to get fish details');
}
})
.catch(err => {
console.error('Error fetching fish details:', err);
})
.finally(() => {
setIsLoading(false);
console.log('loading ended')
})
}, [fishId]);
View that is returned
return (
<ScrollView style={styles.container}>
{isLoading ? (<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<ActivityIndicator size="large" animating={true}/>
</View>) : <View style={styles.content}> .... </View>
Would be grateful for an explanation about this ‘Loading…’ component and for all other advices.
I’ve tried to search google and documentation about the component and couldn’t find anything.
2
Answers
You can try this
Return a promise