We use POST requests to send data from our app to a server. The Fetch API helps us do this easily.
Fetch API for POST requests in 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.
fetch('https://example.com/api', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Anna' }) })
fetch('https://example.com/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'user1', password: 'pass123' }) })
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.
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> ); }
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.
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.
Practice
Solution
Step 1: Understand POST request purpose
POST requests are used to send data to a server, unlike GET which retrieves data.Step 2: Match Fetch API usage
Using Fetch with method 'POST' means sending data from the app to the server.Final Answer:
To send data from the app to a server -> Option CQuick Check:
POST request = send data [OK]
- Confusing POST with GET method
- Thinking POST only updates local state
- Assuming POST deletes data
Solution
Step 1: Identify HTTP method for POST
The method property in Fetch options must be 'POST' to send data.Step 2: Check options object
Only fetch(url, { method: 'POST' }) uses method: 'POST' correctly.Final Answer:
fetch(url, { method: 'POST' }) -> Option AQuick Check:
Fetch POST syntax = method: 'POST' [OK]
- Using method: 'GET' for sending data
- Confusing PUT or DELETE with POST
- Omitting the method property
fetch('https://example.com/api', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'John' })
})
.then(response => response.json())
.then(data => console.log(data.message))
.catch(error => console.error(error));
Assuming the server responds with {"message": "Success"}.Solution
Step 1: Understand fetch and JSON parsing
The fetch call sends a POST request with JSON body and parses the JSON response.Step 2: Check console.log output
Since server returns {"message": "Success"}, data.message is 'Success', so it logs 'Success'.Final Answer:
Logs 'Success' to the console -> Option DQuick Check:
response.json() = parsed JSON, data.message = 'Success' [OK]
- Not parsing response as JSON
- Logging response instead of data.message
- Syntax errors in JSON.stringify
fetch('https://api.example.com/data', {
method: 'POST',
body: { name: 'Alice' }
})Solution
Step 1: Check body format in fetch POST
The body must be a string, usually JSON stringified, not a plain object.Step 2: Identify missing JSON.stringify
Here, body is an object { name: 'Alice' } which causes an error; it should be JSON.stringify({ name: 'Alice' }).Final Answer:
body should be a JSON string, not an object -> Option BQuick Check:
body = JSON.stringify(object) [OK]
- Passing object directly as body
- Forgetting Content-Type header
- Using wrong HTTP method
async function sendData() {
try {
const response = await fetch('https://api.example.com/user', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'user1' })
});
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
B) async function sendData() {
const response = fetch('https://api.example.com/user', {
method: 'POST',
body: { username: 'user1' }
});
const data = response.json();
console.log(data);
}
C) function sendData() {
fetch('https://api.example.com/user', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'user1' })
})
.then(response => response.text())
.then(text => console.log(text))
.catch(error => console.error(error));
}
D) async function sendData() {
try {
const response = await fetch('https://api.example.com/user');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}Solution
Step 1: Check async/await usage and POST setup
Correct async/await POST with JSON body and error handling uses async/await correctly, sets method to 'POST', includes headers, and stringifies body.Step 2: Verify error handling and response parsing
Correct async/await POST with JSON body and error handling has try/catch for errors and parses response as JSON, then logs data.Final Answer:
Correct async/await POST with JSON body and error handling -> Option AQuick Check:
Async POST with try/catch = Correct async/await POST with JSON body and error handling [OK]
- Not awaiting fetch or response.json()
- Not stringifying body object
- Missing headers for JSON content
- Not handling errors
Ready to prove it?
Pass the test and this pattern moves unknown
