Complete the code to import the React hook used for managing state.
import React, { [1] } from 'react';
The useState hook is used to manage state in functional components, which is essential for handling loading states.
Complete the code to fetch data inside a React effect hook.
useEffect(() => {
fetch('/api/data')
.then(response => response.json())
.then(data => setData(data))
.finally(() => set[1](false));
}, []);The state variable for loading is usually named loading in camelCase. The setter function is setLoading, so here we call setLoading(false) to indicate loading is done.
Fix the error in the conditional rendering to show loading text.
if ([1]) { return <p>Loading...</p>; }
setLoading instead of the state variable.The variable loading holds the boolean state for loading. We check it to decide whether to show the loading message. setLoading is a function and cannot be used here.
Fill both blanks to initialize loading state and data state using React hooks.
const [[1], setLoading] = useState(true); const [[2], setData] = useState(null);
We initialize loading state as true because data is loading initially. The data state is named data and starts as null.
Fill all three blanks to render data or loading message conditionally.
return ( <main> { [1] ? ( <p>Loading...</p> ) : ( <ul> { [2]?.map(item => ( <li key={item.id}>[3]</li> ))} </ul> )} </main> );
We check loading to show the loading message. When not loading, we map over data to render each item.name inside list items.