Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Created February 21, 2025 12:08
Show Gist options
  • Save karol-majewski/5a94706c10f85fd414725aebd2af5f58 to your computer and use it in GitHub Desktop.
Save karol-majewski/5a94706c10f85fd414725aebd2af5f58 to your computer and use it in GitHub Desktop.
Fetching Next.js routes with Suspense
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