Complete the code to show a loading spinner while data is loading.
import React, { useState, useEffect } from 'react'; import { View, ActivityIndicator, Text } from 'react-native'; export default function App() { const [loading, setLoading] = useState(true); useEffect(() => { setTimeout(() => setLoading(false), 2000); }, []); if ([1]) { return <ActivityIndicator size="large" />; } return <Text>Data loaded!</Text>; }
The loading state is true while data is loading, so we check if (loading) to show the spinner.
Complete the code to display an error message when there is an error.
import React, { useState } from 'react'; import { View, Text } from 'react-native'; export default function App() { const [error, setError] = useState(null); return ( <View> {error && <Text style={{ color: 'red' }}>{ [1] }</Text>} <Text>Content goes here</Text> </View> ); }
error.message when error is a string.setError instead of the error value.The error state holds the error message string, so we display it directly.
Fix the error in the code to correctly show loading, error, or data states.
import React, { useState, useEffect } from 'react'; import { View, Text, ActivityIndicator } from 'react-native'; export default function App() { const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [data, setData] = useState(null); useEffect(() => { fetch('https://example.com/data') .then(response => response.json()) .then(json => { setData(json); setLoading(false); }) .catch(err => { setError(err.message); setLoading(false); }); }, []); if ([1]) { return <ActivityIndicator size="large" />; } if (error) { return <Text>Error: {error}</Text>; } return <Text>Data: {JSON.stringify(data)}</Text>; }
The loading spinner should show while loading is true, so the condition is if (loading).
Fill both blanks to create a conditional rendering that shows loading or error messages.
function StatusMessage({ loading, error }) {
return (
<View>
{loading ? <Text>[1]</Text> : error && <Text style={{ color: 'red' }}>[2]</Text>}
</View>
);
}When loading is true, show "Loading...". If not loading but error exists, show "Error occurred".
Fill all three blanks to create a component that shows loading, error, or data text.
function DataDisplay({ loading, error, data }) {
if ([1]) return <Text>Loading...</Text>;
if ([2]) return <Text style={{ color: 'red' }}>Error: {error}</Text>;
return <Text>Data: { [3] }</Text>;
}Check loading first to show loading text, then error to show error, else show data.