Complete the code to fetch server state data in a Next.js Server Component.
export default async function Page() {
const data = await fetch('/api/data').then(res => res.[1]())
return <div>{JSON.stringify(data)}</div>
}The json() method parses the response as JSON, which is typical for server state fetched from APIs.
Complete the code to update client state using React's useState hook.
import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return <button onClick={() => setCount([1])}>{count}</button> }
To increment the count on each click, we update state by adding 1 to the current count.
Fix the error in this client component that fetches server state incorrectly.
import { useEffect, useState } from 'react'; export default function Data() { const [data, setData] = useState(null); useEffect(() => { fetch('/api/data').then(res => res.json()).then(json => setData([1])); }, []); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; }
The fetched JSON data is passed to setData to update the client state correctly.
Fill both blanks to create a client component that fetches server state and updates client state.
import { useState, useEffect } from 'react'; export default function UserList() { const [users, setUsers] = useState([1]); useEffect(() => { fetch('/api/users').then(res => res.[2]()).then(data => setUsers(data)); }, []); return <ul>{users.map(user => <li key={user.id}>{user.name}</li>)}</ul>; }
Initialize client state with an empty array to map over, and parse the fetch response as JSON.
Fill all three blanks to correctly fetch server state in a Server Component and pass it as client state to a Client Component.
import ClientComponent from './ClientComponent'; export default async function ServerComponent() { const data = await fetch('/api/items').then(res => res.[1]()); return <ClientComponent initialData=[2] />; } // ClientComponent.js import { useState } from 'react'; export default function ClientComponent({ initialData }) { const [items, setItems] = useState([3]); return <div>{items.length} items loaded</div>; }
The server fetches JSON data, passes it as initialData prop, and the client initializes state with that prop.