0
0
React Nativemobile~20 mins

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

Choose your learning style9 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