How to fetch API data during the launch screen?

Viewed 27

I have react native app using the default template which includes the default launch screen. In release mode, the launch screen only showed for a fraction of a second so I added the below (to AppDelegate) to force it to pause for 2 seconds.

[NSThread sleepForTimeInterval:2.000];

My question is: is there a way to call my api to load data during this pause time?

Presently after the launch screen my main app screen loads which calls an API on mount and displays the data. It would be ideal if I could pre-fetch the data to avoid the wait time after the main app screen loads.

This is the way I call my api on mount of the app:

  useEffect(() => {

    (async function (){

         const response = await fetch('https://myapi...');
         ...
         ...

    })();

  }, []);
1 Answers

You can add a splash screen, And that be your first screen , and on that's useEffect call API and on success of api you can navigate to your destined screen.

https://snack.expo.dev/jG_yuC0mG

check the code please

import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}

function SplashScreen({ navigation }) {
  React.useEffect(() => {
    // call api here
    return new Promise((resolve,reject) => {
      setTimeout(() => {
        navigation.navigate("Home")
        resolve()
      },5000)
    })

  },[navigation])
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Splash Screen</Text>
     <Text> Navigating to home in 5 secs</Text>
    </View>
  );
}

function DetailsScreen() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
    </View>
  );
}

const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Splash">
        <Stack.Screen name="Splash" component={SplashScreen} />
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

Hope it helps, feel free for doubts

Related