What is Networking

Many mobile apps need to load resources from a remote URL. You may want to make a POST/GET request to a REST API

Examples

GET (Fetching movies from REST endpoint and display as list)


import React, {useEffect, useState} from 'react';                       //1
import {ActivityIndicator, FlatList, Text, View} from 'react-native';

type Movie = {
    id: string;
    title: string;
    releaseYear: string;
};

const App = () => {
    const [isLoading, setLoading] = useState(true);                     //2
    const [data, setData] = useState<Movie[]>([]);

    const getMovies = async () => {
    try {
        const response = await fetch('https://reactnative.dev/movies.json');    //3
        const json = await response.json();
        setData(json.movies);
    } catch (error) {
        console.error(error);
    } finally {
        setLoading(false);
    }
    };

    useEffect(() => {                                                           //4
        getMovies();
    }, []);

    return (
    <View style={{flex: 1, padding: 24}}>                                    //5
    {isLoading ? (
        <ActivityIndicator />
    ) : (
        <View>
        <View style={{flexDirection: 'row', backgroundColor: '#f0f0f0'}}>
            <Text style={{flex: 1, fontWeight: 'bold'}}>Title</Text>
            <Text style={{flex: 1, fontWeight: 'bold'}}>Release Year</Text>
        </View>
        <FlatList                                                            //6
            data={data}
            keyExtractor={({id}) => id}
            renderItem={({item}) => (
            <View style={{flexDirection: 'row'}}>
                <Text style={{flex: 1}}>{item.title}</Text>
                <Text style={{flex: 1}}>{item.releaseYear}</Text>
            </View>
            )}
        />
        </View>
    )}
    </View>
    );
};

export default App;
                
Fetch From REST endpoint

1. import react hooks useEffect, useState
2. Taken 2 variables
  isLoading: Tracks whether the data is still being fetched. Initially set to true and switched to false when loading is complete
  data: Stores the list of movies fetched from the API
3. fetch() = HTTP GET.
  response.json(): Converts the response into a JSON object.
  setData(): Sets the movies into data variable
  setLoading(false): Stops the loading indicator once data is fetched.
4. Use useEffect hook. useEffect ensures function is called only once after re-render
5. 2 View blocks
  Outer View: wraps for consistency and padding
  Inner View: Contains the FlatList and its header, & in FlatList data recieved from REST endpoint is rendered
6. FlatList explanation
  data: The array of items to render.
  keyExtractor: Provides a unique key for each item, which is critical for performance.
  renderItem: A function that renders each item in the list.