React Native hỗ trợ Fetch API (chuẩn web) để thực hiện request HTTP. Cú pháp tương tự XMLHttpRequest nhưng dùng Promise, dễ đọc hơn.
Cú pháp cơ bản
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Ví dụ hoàn chỉnh: GET dữ liệu và hiển thị
import React, { Component } from 'react';
import { Text, View, StyleSheet, ActivityIndicator } from 'react-native';
class HttpExample extends Component {
state = {
data: null,
loading: true,
error: null,
};
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'GET',
})
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then(responseJson => {
this.setState({ data: responseJson, loading: false });
})
.catch(error => {
this.setState({ error: error.message, loading: false });
});
}
render() {
const { data, loading, error } = this.state;
if (loading) {
return (
Đang tải...
);
}
if (error) {
return Lỗi: {error} ;
}
return (
{data.title}
{data.body}
);
}
}
const styles = StyleSheet.create({
centered: { flex: 1, justifyContent: 'center', alignItems: 'center' },
container: { flex: 1, padding: 20 },
title: { fontSize: 20, fontWeight: 'bold', marginBottom: 10 },
body: { fontSize: 16, lineHeight: 24 },
error: { color: 'red', textAlign: 'center', marginTop: 20 },
});
const App = () => ;
export default App;
Dữ liệu trả về mẫu
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Các phương thức HTTP phổ biến
| Method | Mô tả | Ví dụ options |
|---|---|---|
| GET | Lấy dữ liệu | { method: 'GET' } |
| POST | Gửi dữ liệu mới | { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) } |
| PUT | Cập nhật toàn bộ | Tương tự POST |
| PATCH | Cập nhật một phần | Tương tự POST |
| DELETE | Xóa dữ liệu | { method: 'DELETE' } |
Ví dụ POST dữ liệu
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: 'New Post',
body: 'Content of new post',
userId: 1,
}),
})
.then(res => res.json())
.then(data => console.log('Created:', data))
.catch(err => console.error(err));
Best Practices
- Luôn kiểm tra
response.oktrước khi parse JSON. - Xử lý lỗi mạng (catch) và lỗi HTTP (status != 2xx).
- Dùng
AbortControllerđể hủy request khi component unmount (tránh memory leak). - Cho production, cân nhắc thư viện
axioshoặcreact-query/tanstack-queryđể caching, retry, deduping tự động.