Complete the code to fetch data from two APIs in parallel using Promise.all.
const fetchData = async () => {
const [data1, data2] = await [1]([
fetch('/api/data1'),
fetch('/api/data2')
]);
return [await data1.json(), await data2.json()];
};Use Promise.all to run multiple promises in parallel and wait for all to complete.
Complete the code to destructure the JSON results from the fetched responses.
const [json1, json2] = await Promise.all([
response1.[1](),
response2.json()
]);Use json() to parse the response body as JSON.
Fix the error in the code to correctly fetch and parse data in parallel.
const [data1, data2] = await Promise.all([ fetch('/api/data1').[1](), fetch('/api/data2').[2]() ]);
Each fetch returns a Response object. You must call json() on it to parse the JSON.
Fill both blanks to create a React component that fetches data in parallel and displays it.
import React, { useState, useEffect } from 'react'; export default function DataComponent() { const [data, setData] = useState(null); useEffect(() => { async function fetchData() { const [res1, res2] = await Promise.all([ fetch('/api/data1'), fetch('/api/data2') ]); const [json1, json2] = await Promise.all([ res1.[1](), res2.[2]() ]); setData({ json1, json2 }); } fetchData(); }, []); if (!data) return <p>Loading...</p>; return <div>{JSON.stringify(data)}</div>; }
Both responses must be parsed as JSON using json() before using the data.
Fill all three blanks to create a Next.js server component that fetches two APIs in parallel and returns combined data.
export default async function Page() {
const [data1, data2] = await Promise.all([
fetch('/api/data1', { cache: '[1]' }),
fetch('/api/data2', { cache: '[2]' })
]).then(responses => Promise.all(responses.map(res => res.[3]())));
return (
<main>
<h1>Data</h1>
<pre>{JSON.stringify({ data1, data2 }, null, 2)}</pre>
</main>
);
}Use no-store to disable caching for fresh data. Parse responses with json().