------------------------- | User List | ------------------------- | Loading... | | | | | | | | | -------------------------
Fetch API for GET requests in React Native - Mini App: Build & Ship
import React, { useState, useEffect } from 'react'; import { View, Text, FlatList, StyleSheet } from 'react-native'; export default function UserList() { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { // TODO: Add fetch code here }, []); return ( <View style={styles.container}> {/* TODO: Add UI rendering code here */} </View> ); } const styles = StyleSheet.create({ container: { flex: 1, padding: 20, backgroundColor: '#fff' }, itemText: { fontSize: 18, paddingVertical: 10 }, errorText: { color: 'red', fontSize: 16 } });
import React, { useState, useEffect } from 'react'; import { View, Text, FlatList, StyleSheet } from 'react-native'; export default function UserList() { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetch('https://jsonplaceholder.typicode.com/users') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { setUsers(data); setLoading(false); }) .catch(err => { setError(err.message); setLoading(false); }); }, []); if (loading) { return ( <View style={styles.container}> <Text>Loading...</Text> </View> ); } if (error) { return ( <View style={styles.container}> <Text style={styles.errorText}>Error: {error}</Text> </View> ); } return ( <View style={styles.container}> <FlatList data={users} keyExtractor={item => item.id.toString()} renderItem={({ item }) => <Text style={styles.itemText}>{item.name}</Text>} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, padding: 20, backgroundColor: '#fff' }, itemText: { fontSize: 18, paddingVertical: 10 }, errorText: { color: 'red', fontSize: 16 } });
This React Native component uses the fetch API to get user data from a public URL. We start by setting loading to true and error to null. Inside useEffect, we call fetch with the URL. We check if the response is okay, then parse it as JSON. The data is saved in the users state, and loading is set to false.
If there is an error during fetching, we catch it and save the error message, also stopping the loading state.
In the UI, if loading is true, we show a simple loading text. If there is an error, we show the error message in red. Otherwise, we display the list of user names using FlatList, which is scrollable and efficient for lists.
This approach keeps the UI responsive and informs the user about the current state (loading, error, or data shown).
------------------------- | User List | ------------------------- | Leanne Graham | | Ervin Howell | | Clementine Bauch | | Patricia Lebsack | | Chelsey Dietrich | | Mrs. Dennis Schulist | | Kurtis Weissnat | | Nicholas Runolfsdottir | | Glenna Reichert | | Clementina DuBuque | -------------------------
Practice
What does the Fetch API do in React Native?
Choose the best description.
Solution
Step 1: Understand Fetch API purpose
The Fetch API is designed to make network requests to get or send data.Step 2: Match description to Fetch API
Only It retrieves data from a web server using HTTP requests. describes retrieving data from a web server, which is what Fetch does.Final Answer:
It retrieves data from a web server using HTTP requests. -> Option AQuick Check:
Fetch API = Data retrieval [OK]
- Confusing Fetch with styling or navigation libraries
- Thinking Fetch stores data locally
- Assuming Fetch only works with JSON
Which of the following is the correct syntax to fetch JSON data from https://api.example.com/data?
fetch(_____).then(response => response.json())Solution
Step 1: Identify correct string syntax in JavaScript
URLs must be passed as strings, enclosed in quotes.Step 2: Choose proper quotes for URL string
'https://api.example.com/data' uses single quotes correctly.Final Answer:
'https://api.example.com/data' -> Option DQuick Check:
URL as string = 'https://api.example.com/data' [OK]
- Not using quotes around the URL
- Using undefined variable url without declaration
- Using double quotes inside double quotes without escaping
What will be logged to the console after running this code?
fetch('https://api.example.com/user')
.then(response => response.json())
.then(data => console.log(data.name))
.catch(error => console.error(error));Assume the server returns { "name": "Alice" }.
Solution
Step 1: Understand fetch and JSON parsing
The fetch call gets the response, then response.json() parses it into an object.Step 2: Access the 'name' property from parsed data
The data object has a 'name' key with value "Alice", so console.log(data.name) prints "Alice".Final Answer:
Alice -> Option CQuick Check:
Parsed JSON name = Alice [OK]
- Logging before JSON parsing
- Trying to access data.name before fetch resolves
- Ignoring asynchronous nature of fetch
Identify the error in this fetch code snippet:
fetch('https://api.example.com/items')
.then(response => response.json)
.then(data => console.log(data))
.catch(error => console.error(error));Solution
Step 1: Check response.json usage
response.json is a function and must be called with parentheses to parse JSON.Step 2: Identify missing parentheses error
The code uses response.json without () which returns the function itself, not the parsed data.Final Answer:
Missing parentheses after response.json() call -> Option AQuick Check:
Call response.json() with () [OK]
- Forgetting parentheses on response.json
- Misplacing catch block
- Using wrong quotes for URL
You want to fetch user data and show a loading message while waiting. Which code snippet correctly handles loading state and errors?
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState(null);
React.useEffect(() => {
fetch('https://api.example.com/user')
.then(res => res.json())
.then(data => {
// handle data
setLoading(false);
})
.catch(err => {
setError(err.message);
setLoading(false);
});
}, []);What is missing to properly show loading and error states?
Solution
Step 1: Understand state variables usage
loading and error states are set correctly during fetch lifecycle.Step 2: Identify missing UI rendering logic
Without UI code that checks loading and error states, user won't see messages.Final Answer:
Render UI that shows loading and error messages based on state -> Option BQuick Check:
Show loading/error UI based on state [OK]
- Not rendering loading or error messages
- Setting loading true too late
- Ignoring error handling in UI
Ready to prove it?
Pass the test and this pattern moves unknown
