Component - Fetch API for POST requests
This React Native component shows how to send data to a server using the Fetch API with a POST request. It has a button that, when pressed, sends a simple message to a fake API and shows the response.
This React Native component shows how to send data to a server using the Fetch API with a POST request. It has a button that, when pressed, sends a simple message to a fake API and shows the response.
App
├── View
│ ├── Text ("Press the button to send POST request")
│ ├── Button ("Send POST")
│ └── Text (response message)
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"}.fetch('https://api.example.com/data', {
method: 'POST',
body: { name: 'Alice' }
})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);
}
}Pass the test and this pattern moves unknown