0
0
NextJSframework~10 mins

Mocking data fetching in NextJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the React hook used for state management.

NextJS
import React, { [1] } from 'react';
Drag options to blanks, or click blank then click option'
AuseState
BuseEffect
CuseContext
DuseRef
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing useEffect instead of useState
Confusing useContext with useState
2fill in blank
medium

Complete the code to fetch data inside a React effect hook.

NextJS
useEffect(() => {
  async function fetchData() {
    const response = await fetch('/api/data');
    const data = await response.[1]();
    setData(data);
  }
  fetchData();
}, []);
Drag options to blanks, or click blank then click option'
Atext
Bjson
Cblob
DformData
Attempts:
3 left
💡 Hint
Common Mistakes
Using text() which returns plain text
Using blob() which returns binary data
3fill in blank
hard

Fix the error in the mock fetch function to return a resolved promise with JSON data.

NextJS
global.fetch = jest.fn(() =>
  Promise.[1]({
    json: () => Promise.resolve({ message: 'Hello' })
  })
);
Drag options to blanks, or click blank then click option'
Arace
Breject
Cresolve
Dall
Attempts:
3 left
💡 Hint
Common Mistakes
Using reject which causes the promise to fail
Using all or race which are for multiple promises
4fill in blank
hard

Fill both blanks to create a mock response with a delay and JSON data.

NextJS
global.fetch = jest.fn(() =>
  new Promise(([1], reject) => {
    setTimeout(() => [2]({ json: () => Promise.resolve({ success: true }) }), 100);
  })
);
Drag options to blanks, or click blank then click option'
Aresolve
Breject
CresolveData
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using reject instead of resolve
Using return which is not a function parameter
5fill in blank
hard

Fill all three blanks to create a React component that fetches mocked data and displays it.

NextJS
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>;
}
Drag options to blanks, or click blank then click option'
AuseState
BuseEffect
Cjson
DuseRef
Attempts:
3 left
💡 Hint
Common Mistakes
Using useEffect instead of useState for state
Using text() instead of json() to parse response