Back to Tutorials

Building a Mobile App with Cloud APIs: React Native Example

Introduction

Learn how to build a mobile application that connects to cloud APIs. We'll use React Native to create a cross-platform app that fetches data from a cloud backend.

Project Setup

# Install React Native CLI
npm install -g react-native-cli

# Create new project
npx react-native init MyCloudApp
cd MyCloudApp

# Install dependencies
npm install axios

Creating API Service

// services/api.js
import axios from 'axios';

const API_URL = 'https://your-api.com/api';

export const apiService = {
  async getData() {
    try {
      const response = await axios.get(`${API_URL}/data`);
      return response.data;
    } catch (error) {
      console.error('API Error:', error);
      throw error;
    }
  },
  
  async postData(data) {
    try {
      const response = await axios.post(`${API_URL}/data`, data);
      return response.data;
    } catch (error) {
      console.error('API Error:', error);
      throw error;
    }
  }
};

Using API in Components

// App.js
import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, Button } from 'react-native';
import { apiService } from './services/api';

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

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

  const loadData = async () => {
    try {
      setLoading(true);
      const result = await apiService.getData();
      setData(result);
    } catch (error) {
      console.error('Failed to load data', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <View style={{ padding: 20 }}>
      <Text style={{ fontSize: 24, marginBottom: 20 }}>Cloud Data App</Text>
      {loading ? (
        <Text>Loading...</Text>
      ) : (
        <FlatList
          data={data}
          keyExtractor={(item) => item.id.toString()}
          renderItem={({ item }) => (
            <View style={{ padding: 10, marginBottom: 10, backgroundColor: '#f0f0f0' }}>
              <Text>{item.title}</Text>
            </View>
          )}
        />
      )}
      <Button title="Refresh" onPress={loadData} />
    </View>
  );
}

Error Handling

Always handle API errors gracefully:

try {
  const data = await apiService.getData();
  // Handle success
} catch (error) {
  if (error.response) {
    // Server responded with error
    console.error('Server error:', error.response.status);
  } else if (error.request) {
    // Request made but no response
    console.error('Network error');
  } else {
    // Something else happened
    console.error('Error:', error.message);
  }
}

Best Practices

  • Use environment variables for API URLs
  • Implement loading states
  • Handle offline scenarios
  • Cache API responses when appropriate
  • Implement retry logic for failed requests