Quick Start Guide
Learn how to instantiate the client, configure baseURL defaults, and send your first GET and POST requests in under two minutes.
Step 1: Create a Client Instance
Create an API service file in your application where you configure client defaults such as the base URL, global timeout, and headers:
src/services/api.ts
typescript
// src/services/api.ts
import { createClient } from 'react-native-fetch-client';
export const api = createClient({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 10000,
headers: {
Accept: 'application/json',
},
});Step 2: Send a GET Request
Pass your TypeScript data type generic to api.get<T>(). The resulting response.data is automatically parsed as JSON and typed:
src/features/posts.ts
typescript
import { api } from './services/api';
interface Post {
id: number;
title: string;
body: string;
userId: number;
}
async function fetchPosts() {
// Strongly-typed response
const response = await api.get<Post[]>('/posts');
console.log('Status code:', response.status); // 200
console.log('Round-trip time:', response.durationMs, 'ms');
console.log('Data:', response.data);
return response.data;
}Step 3: Send a POST Request
Sending JSON bodies is simple. Just pass the JavaScript object as the second argument. The client automatically stringifies the body and sets the Content-Type: application/json header:
typescript
async function createPost() {
const newPost = {
title: 'Testing react-native-fetch-client',
body: 'Modern networking made easy',
userId: 1,
};
const response = await api.post<Post>('/posts', newPost);
console.log('Created ID:', response.data.id);
}Step 4: Go/Rust-Style Safe Requests (Optional)
Tired of wrapping every API call in verbose try / catch blocks? Use the api.safe namespace to get clean [data, error] tuples:
typescript
// No try/catch block needed!
const [posts, error] = await api.safe.get<Post[]>('/posts');
if (error) {
// error is a strongly typed FetchNativeError
console.error('Could not load posts:', error.message);
return;
}
console.log('Loaded safely:', posts);Default Singleton vs createClient
You can also import the default client directly if you prefer one-liners without creating an instance:
import client from 'react-native-fetch-client';
const res = await client.get('https://api.example.com/items');
const res = await client.get('https://api.example.com/items');