techStackGuru

React Native Api call


Fetch API

JavaScript provides fetch(), a built-in method for fetching resources from an API such as data over the network. Like JavaScript, React Native lets you fetch data from an API using fetch().

fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((json) => console.log(json))
.catch((error) => console.error(error))

Headers

fetch('https://api.example.com/data', {
    headers: {
      'Authorization': 'Bearer token123',
      'Content-Type': 'application/json'
    }
  })

Example 1: Fetch API

import React, { useState, useEffect } from 'react';
import { View, Text, Button } from 'react-native';

const ApiExample = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
      const result = await response.json();

      setData(result);
      setLoading(false);
    } catch (error) {
      setError(error);
      setLoading(false);
    }
  };

  return (
    <View>
      {loading && <Text>Loading...</Text>}
      {error && <Text>Error: {error.message}</Text>}
      {data && (
        <View>
          <Text>Title: {data.title}</Text>
          <Text>Completed: {data.completed ? 'Yes' : 'No'}</Text>
        </View>
      )}
      <Button title="Fetch Data" onPress={fetchData} />
    </View>
  );
};

export default ApiExample;

Example 2: Fetch API

import React, { useEffect, useState } from 'react';
import { ScrollView, StyleSheet, Text, View } from 'react-native';

const ExampleAPIs = () => {

    const [todos, setTodos] = useState();

    const getTodoData = () => {
        fetch('https://jsonplaceholder.typicode.com/todos')
            .then(response => response.json())
            .then((json) => {
                setTodos(json);
                console.log(json)
            })
    }

    useEffect(() => {
        getTodoData();
    }, [])

    return (
        <View style={styles.container}>
            <Text>Integrating APIs</Text>

            <ScrollView>
                {!!todos?.length && todos?.map((todo) => {
                    return (
                        <View style={styles.todo}>
                            <Text>{todo?.title}</Text>
                        </View>
                    )
                })}
            </ScrollView>
        </View>
    )
}

export default ExampleAPIs

const styles = StyleSheet.create({
    container: {
        paddingHorizontal: 16,
    },

    todo: {
        width: '100%',
        marginVertical: 16,
        paddingHorizontal: 8,
        justifyContent: 'center',
        alignItems: 'center',
        height: 50,
        borderRadius: 5,
        backgroundColor: 'lightgreen'
    }
})

Using axios

First, you need to install Axios.

npm install axios

You can now use Axios in your component.

Example 3: Axios

import React, { useState, useEffect } from 'react';
import { View, Text, Button } from 'react-native';
import axios from 'axios';

const ApiExampleWithAxiosAndHeaders = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const response = await axios.get('https://jsonplaceholder.typicode.com/todos/1', {
        headers: {
          'Content-Type': 'application/json',
          // Add any additional headers your API requires
          // 'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
        },
      });

      // Axios automatically handles the response status
      const result = response.data;

      setData(result);
      setLoading(false);
    } catch (error) {
      setError(error);
      setLoading(false);
    }
  };

  return (
    <View>
      {loading && <Text>Loading...</Text>}
      {error && <Text>Error: {error.message}</Text>}
      {data && (
        <View>
          <Text>Title: {data.title}</Text>
          <Text>Completed: {data.completed ? 'Yes' : 'No'}</Text>
        </View>
      )}
      <Button title="Fetch Data" onPress={fetchData} />
    </View>
  );
};

export default ApiExampleWithAxiosAndHeaders;

A GET request is made using the axios.get method imported from Axios. The response data can be accessed using response.data, which is automatically handled by Axios.