We use POST requests to send data from our app to a server. The Fetch API helps us do this easily.
0
0
Fetch API for POST requests in React Native
Introduction
When a user submits a form and you want to save their data online.
When you need to send login details to check if a user is allowed in.
When uploading a photo or file from your app to a website.
When sending feedback or messages from the app to a server.
Syntax
React Native
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(result => {
// handle result
})
.catch(error => {
// handle error
});The method must be 'POST' to send data.
Use JSON.stringify to convert your data object into a string.
Examples
Sends a simple object with a name to the server.
React Native
fetch('https://example.com/api', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Anna' }) })
Sends login details securely to check user access.
React Native
fetch('https://example.com/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'user1', password: 'pass123' }) })
Sample App
This React Native app has a button. When pressed, it sends a POST request to create a post on a test server. It then shows the new post ID or an error message.
React Native
import React, { useState } from 'react'; import { View, Button, Text } from 'react-native'; export default function App() { const [responseMessage, setResponseMessage] = useState(''); const sendData = async () => { try { const response = await fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'Hello', body: 'This is a test', userId: 1 }) }); const data = await response.json(); setResponseMessage('Post created with ID: ' + data.id); } catch (error) { setResponseMessage('Error: ' + error.message); } }; return ( <View style={{ padding: 20, marginTop: 50 }}> <Button title="Send POST Request" onPress={sendData} /> <Text style={{ marginTop: 20 }}>{responseMessage}</Text> </View> ); }
OutputSuccess
Important Notes
Always set the Content-Type header to 'application/json' when sending JSON data.
Use async/await for cleaner code and easier error handling.
Test your POST requests with free services like jsonplaceholder.typicode.com before using your real server.
Summary
POST requests send data from your app to a server.
Use Fetch API with method 'POST' and JSON.stringify your data.
Handle the server response to update your app UI or show messages.