Fetching Data from an API in React Native with Expo


Fetching data from an API is a fundamental part of building dynamic mobile applications. In this guide, we will explore how to fetch data in a React Native Expo project using the built-in fetch API and Axios.

1. Setting Up the Project

Ensure you have a React Native Expo project set up. If not, create one using:

npx create-expo-app myApp
cd myApp
npm start

2. Fetching Data with Fetch API

The fetch API is a simple way to request data from a server. Let’s create a component that fetches and displays data from a public API.






Creating a Data Fetching Component

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

export default function FetchData() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(json => {
        setData(json);
        setLoading(false);
      })
      .catch(error => console.error(error));
  }, []);

  if (loading) {
    return <ActivityIndicator size="large" color="#0000ff" />;
  }

  return (
    <View>
      <FlatList
        data={data}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <Text>{item.title}</Text>
        )}
      />
    </View>
  );
}

3. Using Axios for API Requests

Axios is a popular library that simplifies API calls and handles errors more efficiently.

Installing Axios

npm install axios

Fetching Data with Axios

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

export default function FetchData() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        setData(response.data);
        setLoading(false);
      })
      .catch(error => console.error(error));
  }, []);

  if (loading) {
    return <ActivityIndicator size="large" color="#0000ff" />;
  }

  return (
    <View>
      <FlatList
        data={data}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <Text>{item.title}</Text>
        )}
      />
    </View>
  );
}

4. Conclusion

Fetching data in React Native Expo is straightforward using either the fetch API or Axios. Axios provides better error handling and automatic JSON conversion, making it a preferred choice for many developers. Try experimenting with different APIs to build a more interactive app! πŸš€

Comments

Popular posts from this blog

State Management in React Native with Expo: A Beginner’s Guide

How to Set Up React Native with Expo πŸš€