0
0
React Nativemobile~5 mins

Fetch API for GET requests in React Native

Choose your learning style9 modes available
Introduction

The Fetch API helps your app get data from the internet. It lets you ask a website for information and use it inside your app.

When you want to show weather info from an online service.
When your app needs to load user profiles from a server.
When you want to get a list of news articles from a website.
When you need to fetch images or data from a public API.
When your app updates content without restarting.
Syntax
React Native
fetch(url)
  .then(response => response.json())
  .then(data => {
    // use the data here
  })
  .catch(error => {
    // handle errors here
  });

fetch(url) starts the request to get data from the web address.

response.json() converts the response into a usable JavaScript object.

Examples
Simple fetch to get data and print it in the console.
React Native
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data));
Fetch with error handling to catch problems like no internet.
React Native
fetch('https://api.example.com/users')
  .then(response => response.json())
  .then(users => {
    // show users in the app
  })
  .catch(error => console.error('Error:', error));
Sample App

This React Native app fetches a post from a public API and shows its title and body. It shows a loading spinner while waiting and an error message if something goes wrong.

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

export default function App() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

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

  if (loading) {
    return <View style={styles.container}><ActivityIndicator size="large" /></View>;
  }

  if (error) {
    return <View style={styles.container}><Text>Error: {error}</Text></View>;
  }

  return (
    <View style={styles.container}>
      <Text style={styles.title}>{data.title}</Text>
      <Text>{data.body}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 20
  },
  title: {
    fontWeight: 'bold',
    fontSize: 18,
    marginBottom: 10
  }
});
OutputSuccess
Important Notes

Always handle errors with catch to avoid app crashes.

Use useEffect in React Native to fetch data when the component loads.

Show a loading indicator so users know data is coming.

Summary

The Fetch API gets data from the internet easily.

Use fetch(url).then(response => response.json()) to get JSON data.

Handle loading and errors for a smooth user experience.