We use JSON response parsing to read data sent from a server in a format our app can understand and use.
JSON response parsing in React Native
fetch('https://example.com/data')
.then(response => response.json())
.then(data => {
// use the parsed data here
})
.catch(error => {
// handle errors here
});fetch gets data from a URL.
response.json() converts the response to a JavaScript object.
fetch('https://api.example.com/users')
.then(res => res.json())
.then(users => console.log(users));async function getData() { const response = await fetch('https://api.example.com/data'); const jsonData = await response.json(); console.log(jsonData); }
This React Native app fetches a todo item from a test API, parses the JSON response, and shows the todo details on screen. It also shows a loading spinner while waiting and an error message if something goes wrong.
import React, { useState, useEffect } from 'react'; import { View, Text, ActivityIndicator } from 'react-native'; export default function App() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(json => { setData(json); setLoading(false); }) .catch(err => { setError(err.message); setLoading(false); }); }, []); if (loading) return <ActivityIndicator size="large" />; if (error) return <Text>Error: {error}</Text>; return ( <View style={{ padding: 20 }}> <Text>Todo ID: {data.id}</Text> <Text>Title: {data.title}</Text> <Text>Completed: {data.completed ? 'Yes' : 'No'}</Text> </View> ); }
Always handle errors when fetching data to avoid app crashes.
Use loading indicators to improve user experience while waiting for data.
JSON parsing turns text data into objects you can use in your app.
JSON response parsing lets your app understand data from servers.
Use fetch and response.json() to get and parse JSON.
Handle loading and errors for smooth app behavior.
Practice
response.json() do in React Native when fetching data?Solution
Step 1: Understand the fetch response
The fetch API returns a response object that contains the raw data from the server.Step 2: Use response.json() to parse data
Theresponse.json()method reads the raw response and converts it into a usable JavaScript object.Final Answer:
It converts the server response into a JavaScript object. -> Option CQuick Check:
response.json() = parse JSON [OK]
- Thinking response.json() sends data to server
- Assuming response.json() displays data directly
- Confusing response.json() with stopping fetch
Solution
Step 1: Recall fetch syntax
The fetch function returns a promise with a response object.Step 2: Use response.json() to parse JSON
The correct method to parse JSON from the response isresponse.json(), which returns a promise with the parsed object.Final Answer:
fetch(url).then(response => response.json()) -> Option AQuick Check:
Correct fetch JSON syntax = fetch(url).then(response => response.json()) [OK]
- Using response.text() instead of response.json()
- Calling json() directly on fetch without then
- Using non-existent parseJSON() method
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data.name))
.catch(error => console.error(error));What will be logged if the JSON response is
{"name": "Alice", "age": 25}?Solution
Step 1: Parse JSON response
The response JSON is parsed into an object: {name: "Alice", age: 25}.Step 2: Access the 'name' property
The code logsdata.name, which is "Alice".Final Answer:
"Alice" -> Option AQuick Check:
data.name = "Alice" [OK]
- Logging data instead of data.name
- Expecting age instead of name
- Not parsing JSON before accessing properties
fetch('https://api.example.com/data')
.then(response => response.json)
.then(data => console.log(data))
.catch(error => console.error(error));Solution
Step 1: Check response.json usage
The code usesresponse.jsonwithout parentheses, so it references the function but does not call it.Step 2: Correct function call syntax
It should beresponse.json()to actually parse the JSON.Final Answer:
Missing parentheses after response.json -> Option BQuick Check:
Call response.json() with () [OK]
- Forgetting parentheses after response.json
- Assuming fetch URL is wrong without checking
- Confusing console.log and console.error usage
{"users": [{"id": 1, "name": "Bob"}, {"id": 2, "name": "Carol"}]}How do you extract an array of user names in React Native after parsing?
Solution
Step 1: Understand JSON structure
The JSON has a key "users" which is an array of user objects.Step 2: Use map to extract names
To get all names, usedata.users.map(user => user.name)which creates a new array of names.Final Answer:
data.users.map(user => user.name) -> Option DQuick Check:
Map over data.users to get names [OK]
- Mapping directly on data instead of data.users
- Trying to access data.users.name which is undefined
- Assuming data.names exists
Ready to prove it?
Pass the test and this pattern moves unknown
