Complete the code to memoize the fetch request using a simple cache object.
const cache = {};
export async function fetchData(url) {
if (cache[url]) {
return cache[url];
}
const response = await fetch(url);
const data = await response.json();
cache[url] = [1];
return data;
}The fetched data is stored in the cache object under the URL key to avoid repeated requests.
Complete the React hook to memoize the fetch request result using useState and useEffect.
import { useState, useEffect } from 'react'; export function useFetch(url) { const [data, setData] = useState(null); useEffect(() => { async function fetchData() { const response = await fetch(url); const json = await response.json(); setData([1]); } fetchData(); }, [url]); return data; }
The hook sets the state with the parsed JSON data after fetching.
Fix the error in this Next.js server component to memoize the fetch request result.
import React from 'react'; const cache = new Map(); export default async function Page() { const url = 'https://api.example.com/data'; if (cache.has(url)) { return <pre>{JSON.stringify(cache.get(url), null, 2)}</pre>; } const res = await fetch(url); const data = await res.json(); cache.set(url, [1]); return <pre>{JSON.stringify(data, null, 2)}</pre>; }
The parsed JSON data must be stored in the cache, not the response object or other values.
Fill both blanks to create a memoized fetch function that caches results and returns cached data if available.
const cache = {};
export async function memoFetch(url) {
if ([1]) {
return cache[url];
}
const response = await fetch(url);
const data = await response.json();
[2] = data;
return data;
}The function checks if the URL is cached and returns cached data. Then it stores the fetched data in the cache.
Fill all three blanks to implement a React hook that memoizes fetch results and updates state only when data changes.
import { useState, useEffect, useRef } from 'react'; export function useMemoFetch(url) { const [data, setData] = useState(null); const cache = useRef({}); useEffect(() => { if (cache.current[url]) { setData(cache.current[[1]]); return; } async function fetchData() { const res = await fetch(url); const json = await res.json(); cache.current[[2]] = json; setData(json); } fetchData(); }, [[3]]); return data; }
All blanks relate to the URL string to correctly cache and trigger effect on URL changes.