Complete the code to fetch data from the URL using fetch.
fetch('[1]') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
The fetch function needs the URL string as its first argument to make a GET request.
Complete the code to convert the fetch response to JSON.
fetch('https://api.example.com/data') .then(response => response.[1]()) .then(data => console.log(data));
The response.json() method parses the response body as JSON.
Fix the error in the fetch call to handle errors properly.
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .[1](error => console.error('Error:', error));
The catch method handles errors in the fetch promise chain.
Fill both blanks to create a React Native component that fetches data on button press.
import React, { useState } from 'react'; import { View, Button, Text } from 'react-native'; export default function FetchExample() { const [data, setData] = useState(null); const fetchData = () => { fetch('https://api.example.com/data') .then(response => response.[1]()) .then(json => setData(json)) .catch(error => console.error(error)); }; return ( <View> <Button title="Fetch Data" onPress=[2] /> {data && <Text>{JSON.stringify(data)}</Text>} </View> ); }
response.json() converts the response to JSON.
The onPress prop needs the function reference fetchData without parentheses.
Fill all three blanks to fetch data and display loading status in React Native.
import React, { useState } from 'react'; import { View, Button, Text } from 'react-native'; export default function FetchWithLoading() { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const fetchData = () => { setLoading([1]); fetch('https://api.example.com/data') .then(response => response.[2]()) .then(json => { setData(json); setLoading([3]); }) .catch(error => { console.error(error); setLoading(false); }); }; return ( <View> <Button title="Fetch Data" onPress={fetchData} /> {loading ? <Text>Loading...</Text> : data && <Text>{JSON.stringify(data)}</Text>} </View> ); }
Set loading to true before fetch starts.
Use response.json() to parse.
Set loading to false after data is received.