I’ll walk you through implementing service calls in React Native to retrieve data from a server.
First, let’s look at a basic implementation using the Fetch API, which is built into React Native:
// api.js - Create a service file
const API_URL = 'https://your-api-endpoint.com/api';
export const fetchData = async (endpoint) => {
try {
const response = await fetch(`${API_URL}/${endpoint}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('API request failed:', error);
throw error;
}
};
Now, here’s how you would use this service in a component:
import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, ActivityIndicator } from 'react-native';
import { fetchData } from './api';
const UserList = () => {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const getUsers = async () => {
try {
setLoading(true);
const data = await fetchData('users');
setUsers(data);
setError(null);
} catch (err) {
setError('Failed to fetch users');
console.error(err);
} finally {
setLoading(false);
}
};
getUsers();
}, []);
if (loading) {
return <ActivityIndicator size="large" color="#0000ff" />;
}
if (error) {
return <Text>Error: {error}</Text>;
}
return (
<View>
<FlatList
data={users}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => (
<Text>{item.name}</Text>
)}
/>
</View>
);
};
export default UserList;
For more advanced needs, you might want to use Axios, which offers additional features:
// First, install Axios: npm install axios
// Then create api.js
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://your-api-endpoint.com/api',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// Add request interceptor for things like authentication
apiClient.interceptors.request.use(
(config) => {
// Add auth token to requests
const token = /* get your auth token */;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// Service methods
export const userService = {
getAll: () => apiClient.get('/users'),
getById: (id) => apiClient.get(`/users/${id}`),
create: (data) => apiClient.post('/users', data),
update: (id, data) => apiClient.put(`/users/${id}`, data),
delete: (id) => apiClient.delete(`/users/${id}`),
};
Thank you for reading!