Bird
Raised Fist0
React Nativemobile~20 mins

Fetch API for POST requests in React Native - Mini App: Build & Ship

Choose your learning style10 modes available
Build: PostDataScreen
This screen lets the user send a message to a server using a POST request and shows the server response.
Target UI
-------------------------
| Post Data Screen       |
|-----------------------|
| Message:              |
| [___________________] |
|                       |
| [Send]                |
|                       |
| Response:             |
| [                   ] |
-------------------------
A TextInput for user to type a message
A Send button that triggers a POST request to https://jsonplaceholder.typicode.com/posts
Send the message as JSON in the POST body with key 'title'
Show the server response's 'id' field below the button
Handle loading state and errors gracefully
Starter Code
React Native
import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';

export default function PostDataScreen() {
  const [message, setMessage] = useState('');
  const [responseId, setResponseId] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const sendData = async () => {
    // TODO: Implement POST request using fetch
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Post Data Screen</Text>
      <Text>Message:</Text>
      <TextInput
        style={styles.input}
        value={message}
        onChangeText={setMessage}
        placeholder="Type your message"
        accessibilityLabel="Message input"
      />
      <Button title={loading ? 'Sending...' : 'Send'} onPress={sendData} disabled={loading} accessibilityLabel="Send button" />
      <Text style={styles.responseLabel}>Response:</Text>
      <Text style={styles.responseText}>{responseId ? `ID: ${responseId}` : error ? `Error: ${error}` : ''}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { padding: 20, flex: 1, backgroundColor: '#fff' },
  title: { fontSize: 20, fontWeight: 'bold', marginBottom: 10 },
  input: { borderWidth: 1, borderColor: '#ccc', padding: 8, marginVertical: 10, borderRadius: 4 },
  responseLabel: { marginTop: 20, fontWeight: 'bold' },
  responseText: { marginTop: 5, fontSize: 16 }
});
Task 1
Task 2
Task 3
Task 4
Solution
React Native
import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';

export default function PostDataScreen() {
  const [message, setMessage] = useState('');
  const [responseId, setResponseId] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const sendData = async () => {
    setLoading(true);
    setError(null);
    setResponseId(null);
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: message })
      });
      if (!response.ok) throw new Error('Network response was not ok');
      const data = await response.json();
      setResponseId(data.id);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Post Data Screen</Text>
      <Text>Message:</Text>
      <TextInput
        style={styles.input}
        value={message}
        onChangeText={setMessage}
        placeholder="Type your message"
        accessibilityLabel="Message input"
      />
      <Button title={loading ? 'Sending...' : 'Send'} onPress={sendData} disabled={loading || message.trim() === ''} accessibilityLabel="Send button" />
      <Text style={styles.responseLabel}>Response:</Text>
      <Text style={styles.responseText}>{responseId ? `ID: ${responseId}` : error ? `Error: ${error}` : ''}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { padding: 20, flex: 1, backgroundColor: '#fff' },
  title: { fontSize: 20, fontWeight: 'bold', marginBottom: 10 },
  input: { borderWidth: 1, borderColor: '#ccc', padding: 8, marginVertical: 10, borderRadius: 4 },
  responseLabel: { marginTop: 20, fontWeight: 'bold' },
  responseText: { marginTop: 5, fontSize: 16 }
});

We use React Native's fetch API to send a POST request. The sendData function sets loading to true, clears previous errors and response, then sends the message as JSON with key title. We check if the response is OK, parse the JSON, and update the responseId state with the returned id. Errors are caught and shown to the user. The Send button disables while loading or if the message is empty to prevent invalid requests.

This approach keeps the UI responsive and informs the user about the request status.

Final Result
Completed Screen
-------------------------
| Post Data Screen       |
|-----------------------|
| Message:              |
| [Hello world       ]  |
|                       |
| [Send]                |
|                       |
| Response:             |
| ID: 101               |
-------------------------
User types a message in the input field
User taps Send button
Button shows 'Sending...' and disables
App sends POST request with message
On success, shows 'ID: 101' below
On error, shows error message below
Stretch Goal
Add a clear button to reset the message input and response display
💡 Hint
Add a Button labeled 'Clear' that sets message, responseId, and error states to initial values when pressed

Practice

(1/5)
1. What is the main purpose of using a POST request with the Fetch API in React Native?
easy
A. To delete data from the app
B. To retrieve data from a server
C. To send data from the app to a server
D. To update the app's local state only

Solution

  1. Step 1: Understand POST request purpose

    POST requests are used to send data to a server, unlike GET which retrieves data.
  2. Step 2: Match Fetch API usage

    Using Fetch with method 'POST' means sending data from the app to the server.
  3. Final Answer:

    To send data from the app to a server -> Option C
  4. Quick Check:

    POST request = send data [OK]
Hint: POST means sending data to server, not just getting it [OK]
Common Mistakes:
  • Confusing POST with GET method
  • Thinking POST only updates local state
  • Assuming POST deletes data
2. Which of the following is the correct way to specify a POST request using Fetch API in React Native?
easy
A. fetch(url, { method: 'POST' })
B. fetch(url, { method: 'GET' })
C. fetch(url, { method: 'PUT' })
D. fetch(url, { method: 'DELETE' })

Solution

  1. Step 1: Identify HTTP method for POST

    The method property in Fetch options must be 'POST' to send data.
  2. Step 2: Check options object

    Only fetch(url, { method: 'POST' }) uses method: 'POST' correctly.
  3. Final Answer:

    fetch(url, { method: 'POST' }) -> Option A
  4. Quick Check:

    Fetch POST syntax = method: 'POST' [OK]
Hint: Use method: 'POST' exactly to send data [OK]
Common Mistakes:
  • Using method: 'GET' for sending data
  • Confusing PUT or DELETE with POST
  • Omitting the method property
3. What will be the output of this code snippet in React Native?
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"}.
medium
A. Throws a syntax error
B. Logs undefined to the console
C. Logs the entire response object
D. Logs 'Success' to the console

Solution

  1. Step 1: Understand fetch and JSON parsing

    The fetch call sends a POST request with JSON body and parses the JSON response.
  2. Step 2: Check console.log output

    Since server returns {"message": "Success"}, data.message is 'Success', so it logs 'Success'.
  3. Final Answer:

    Logs 'Success' to the console -> Option D
  4. Quick Check:

    response.json() = parsed JSON, data.message = 'Success' [OK]
Hint: response.json() parses JSON, then access properties [OK]
Common Mistakes:
  • Not parsing response as JSON
  • Logging response instead of data.message
  • Syntax errors in JSON.stringify
4. Identify the error in this React Native POST request code:
fetch('https://api.example.com/data', {
  method: 'POST',
  body: { name: 'Alice' }
})
medium
A. Missing headers for content type
B. body should be a JSON string, not an object
C. method should be 'GET' instead of 'POST'
D. URL is invalid

Solution

  1. Step 1: Check body format in fetch POST

    The body must be a string, usually JSON stringified, not a plain object.
  2. Step 2: Identify missing JSON.stringify

    Here, body is an object { name: 'Alice' } which causes an error; it should be JSON.stringify({ name: 'Alice' }).
  3. Final Answer:

    body should be a JSON string, not an object -> Option B
  4. Quick Check:

    body = JSON.stringify(object) [OK]
Hint: Always JSON.stringify body for POST requests [OK]
Common Mistakes:
  • Passing object directly as body
  • Forgetting Content-Type header
  • Using wrong HTTP method
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);
  }
}
hard
A. Correct async/await POST with JSON body and error handling
B. Missing await and body is not stringified
C. Uses then but parses response as text, not JSON
D. No POST method or body specified

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Correct async/await POST with JSON body and error handling -> Option A
  4. Quick Check:

    Async POST with try/catch = Correct async/await POST with JSON body and error handling [OK]
Hint: Use async/await with try/catch and JSON.stringify body [OK]
Common Mistakes:
  • Not awaiting fetch or response.json()
  • Not stringifying body object
  • Missing headers for JSON content
  • Not handling errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard