Complete the code to fetch data from the backend API.
fetch('https://api.example.com/data') .then(response => response.[1]()) .then(data => console.log(data));
The json() method parses the response as JSON, which is the common data format from APIs.
Complete the code to send a POST request to the backend API.
fetch('https://api.example.com/login', { method: '[1]', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'user', password: 'pass' }) });
POST method is used to send data to the backend, such as login credentials.
Fix the error in the code to correctly handle API response errors.
fetch('https://api.example.com/data') .then(response => { if (!response.[1]) { throw new Error('Network response was not ok'); } return response.json(); }) .catch(error => console.error('Fetch error:', error));
The ok property is a boolean indicating if the response status is in the 200-299 range.
Fill both blanks to create a React Native component that fetches data on button press.
import React, { useState } from 'react'; import { Button, Text, View } from 'react-native'; export default function App() { const [data, setData] = useState(null); const fetchData = async () => { const response = await fetch('https://api.example.com/data'); const json = await response.[1](); setData(json.[2]); }; return ( <View> <Button title="Load Data" onPress={fetchData} /> <Text>{data}</Text> </View> ); }
Use json() to parse the response, then access the result property from the JSON data.
Fill all three blanks to complete the React Native fetch with error handling and loading state.
import React, { useState } from 'react'; import { Button, Text, View, ActivityIndicator } from 'react-native'; export default function App() { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const fetchData = async () => { setLoading(true); setError(null); try { const response = await fetch('https://api.example.com/data'); if (!response.[1]) throw new Error('Error fetching'); const json = await response.[2](); setData(json.[3]); } catch (e) { setError(e.message); } finally { setLoading(false); } }; return ( <View> <Button title="Load" onPress={fetchData} /> {loading && <ActivityIndicator />} {error && <Text>Error: {error}</Text>} {data && <Text>{data}</Text>} </View> ); }
Check ok to confirm response success, parse JSON with json(), then access result property.