5. You want to send user data with a POST request and handle errors gracefully in React Native. Which code snippet correctly implements this with async/await and error handling?
A)
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);
}
}