Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Created February 13, 2025 14:11
Show Gist options
  • Save karol-majewski/f4fa0b10817f22f011b95e3852821962 to your computer and use it in GitHub Desktop.
Save karol-majewski/f4fa0b10817f22f011b95e3852821962 to your computer and use it in GitHub Desktop.
Using Suspense with a callback-based API
const cache = new Map<string, Promise<google.maps.places.PlaceResult>>();
export function useAddress(placeId: string) {
const getPlacesService = useCallback(() => {
return new google.maps.places.PlacesService(document.createElement("div"));
}, []);
// Check if we already have a cached promise for this placeId
if (!cache.has(placeId)) {
const placesService = getPlacesService();
const promise = new Promise<google.maps.places.PlaceResult>(
(resolve, reject) => {
placesService.getDetails(
{
placeId,
fields: ["address_components", "formatted_address"],
},
(place) => {
if (!place) {
return reject(new Error("Place not found"));
}
resolve(place);
},
);
},
);
// Store the promise in the cache
cache.set(placeId, promise);
}
// Use the cached promise
return use(cache.get(placeId)!);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment