Tương Tác API sử dụng React Native Fetch
Để app react native lấy những data từ URL , trong react native người ta sẽ sử dụng Fetch Api.
Fetch sẽ tương tự như là bạn sử dụng XMLHttpRequest hoặc một số framework hỗ trợ khác tương tự.
Theo như docs của Facebook cũng đã đầy đủ rồi, nên trong bài viết này mình sẽ chỉ tóm tắt lại một số ý chính trong việc sử dụng Fetch để lấy data từ API
GET requests
Đầu tiên là GET, sử dụng GET request để lấy data là một trường hợp đơn giản nhất.
Bạn chỉ cần sử dụng Fetch và truyền tham số là link URL của API là ok.
Cách làm như sau:
fetch('link_url_to_endpoint') // truyền link url của api vào
.then(res => { // res chính là response trả về
return res.json() // parse response trả về thành json
})
Sau khi có được response json trả về từ server , ta có thể lấy tiếp các dữ liệu bên trong theo ý của mình
Ví dụ response json trả về của mình sau:
{
"result": "ok",
"data": {
"id": 480,
"email": "[email protected]",
"name": "Hung",
"token": "$2y$10$zOX1qAYaoThDi2QfClj2Su45BTf2lp/Sh5muFWdCDQKB.bV7l/G6S",
"expiry": 0,
"devices": []
},
"errors": []
}
Để lấy được result , data , errors mình sẽ làm như sau:
fetch('your_url')
.then(res => res.json())
.then(resJson => {
console.log(resJson.result)
console.log(resJson.errors)
console.log(resJson.data)
})
POST resquests
Với method POST , chúng ta cũng sẽ làm gần giống với GET.
let secondPara = ""
fetch('your_url', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: firstPara,
secondParam: secondPara,
})
})
Có vài lưu ý nhỏ khi dùng POST đó là :
Phải đảm bảo có headers.
Chuyển thành dạng Json bằng cách sử dụng JSON.stringify trước khi gửi lên.
Nếu là link http thì phải qua Xcode mở Transport Security.
WebSocket Support
Ngoài ra react native còn hỗ trợ Websocket, .
ws.onopen = () => {
// connection opened
ws.send('something'); // send a message
};
ws.onmessage = (e) => {
// a message was received
console.log(e.data);
};
ws.onerror = (e) => {
// an error occurred
console.log(e.message);
};
ws.onclose = (e) => {
// connection closed
console.log(e.code, e.reason);
};
Nguồn tham khảo:
[1].https://facebook.github.io/react-native/docs/network.html
[2.]https://medium.com/@yoniweisbrod/interacting-with-apis-using-react-native-fetch-9733f28566bb
Nguyễn Khánh Hưng