Complete the code to import the React hook used for state management.
import React, { [1] } from 'react';
The useState hook is used to manage state in functional components.
Complete the code to fetch data inside a React effect hook.
useEffect(() => {
async function fetchData() {
const response = await fetch('/api/data');
const data = await response.[1]();
setData(data);
}
fetchData();
}, []);The json() method parses the response body as JSON, which is common for API data.
Fix the error in the mock fetch function to return a resolved promise with JSON data.
global.fetch = jest.fn(() => Promise.[1]({ json: () => Promise.resolve({ message: 'Hello' }) }) );
Use Promise.resolve to return a successful resolved promise with the mock data.
Fill both blanks to create a mock response with a delay and JSON data.
global.fetch = jest.fn(() => new Promise(([1], reject) => { setTimeout(() => [2]({ json: () => Promise.resolve({ success: true }) }), 100); }) );
Both blanks use resolve to fulfill the promise and return the mock JSON data after a delay.
Fill all three blanks to create a React component that fetches mocked data and displays it.
import React, { [1] } from 'react'; export default function MockComponent() { const [data, setData] = [2](null); React.useEffect(() => { async function fetchData() { const response = await fetch('/api/mock'); const json = await response.[3](); setData(json); } fetchData(); }, []); return <div>{data ? data.message : 'Loading...'}</div>; }
The component uses useState to hold data, calls fetch inside useEffect, and parses the response with json().