Created
February 13, 2025 14:11
-
-
Save karol-majewski/f4fa0b10817f22f011b95e3852821962 to your computer and use it in GitHub Desktop.
Using Suspense with a callback-based API
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
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