0
0
React Nativemobile~5 mins

Why API integration connects to backends in React Native

Choose your learning style9 modes available
Introduction

API integration lets your app talk to servers to get or send data. This helps your app show fresh info and work with other services.

When your app needs to show live weather updates from a weather service.
When users log in and you need to check their details on a server.
When your app sends messages or posts to a social media platform.
When you want to load product lists from an online store backend.
When your app saves user preferences or data remotely.
Syntax
React Native
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    // use the data here
  })
  .catch(error => {
    // handle errors here
  });
Use fetch to call APIs in React Native.
Always handle errors to keep your app stable.
Examples
Fetches a list of users and prints it in the console.
React Native
fetch('https://api.example.com/users')
  .then(res => res.json())
  .then(users => console.log(users));
Uses async/await to get items from an API and handle errors.
React Native
async function getData() {
  try {
    const response = await fetch('https://api.example.com/items');
    const items = await response.json();
    console.log(items);
  } catch (error) {
    console.error('Error:', error);
  }
}
Sample App

This React Native app fetches a todo item from a backend API and shows its details. 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 } 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/todos/1')
      .then(response => response.json())
      .then(json => {
        setData(json);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

  if (loading) return <ActivityIndicator size="large" />;
  if (error) return <Text>Error: {error}</Text>;

  return (
    <View style={{ padding: 20 }}>
      <Text>Todo Item:</Text>
      <Text>ID: {data.id}</Text>
      <Text>Title: {data.title}</Text>
      <Text>Completed: {data.completed ? 'Yes' : 'No'}</Text>
    </View>
  );
}
OutputSuccess
Important Notes

APIs let your app get fresh data without updating the app itself.

Always check for errors to avoid app crashes.

Use loading indicators to improve user experience while waiting for data.

Summary

API integration connects your app to backend servers to get or send data.

This helps your app stay updated and interact with other services.

Use fetch or async/await in React Native to call APIs safely.