Created
February 21, 2025 12:08
-
-
Save karol-majewski/5a94706c10f85fd414725aebd2af5f58 to your computer and use it in GitHub Desktop.
Fetching Next.js routes with Suspense
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { use } from "react"; | |
import type { DeliveryAddress } from "./types"; | |
const cache = new Map<string, Promise<DeliveryAddress>>(); | |
export function useDeliveryAddress(userId: string): DeliveryAddress { | |
if (!cache.has(userId)) { | |
const promise = fetch(`/api/user/delivery-address/${userId}`).then( | |
(response) => { | |
if (!response.ok) { | |
throw new Error(`HTTP error! status: ${response.status}`); | |
} | |
return response.json(); | |
}, | |
); | |
cache.set(userId, promise); | |
} | |
return use(cache.get(userId)!); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment