Skip to content

Commit 469d71a

Browse files
committed
fix: prevent api provider race condition, defer loading state update
1 parent 522f8eb commit 469d71a

2 files changed

Lines changed: 42 additions & 3 deletions

File tree

src/components/__tests__/api-provider.test.tsx

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,45 @@ test('sets fetchAppCheckToken on google.maps.Settings after API loads', async ()
244244
expect(settingsInstance.fetchAppCheckToken).toBe(mockFetchToken);
245245
});
246246

247+
test('waits for externally installed importLibrary before marking API as loaded', async () => {
248+
const mockFetchToken = jest.fn().mockResolvedValue({token: 'test-token'});
249+
const getInstanceMock = jest.fn(() => settingsInstance);
250+
251+
google.maps.importLibrary = jest.fn(async () => {
252+
await importLibraryPromise;
253+
254+
return {} as google.maps.MapsLibrary;
255+
}) as typeof google.maps.importLibrary;
256+
google.maps.Settings = undefined as unknown as typeof google.maps.Settings;
257+
258+
render(
259+
<APIProvider apiKey={'apikey'} fetchAppCheckToken={mockFetchToken}>
260+
<ContextSpyComponent />
261+
</APIProvider>
262+
);
263+
264+
await waitFor(() =>
265+
expect(ContextSpyComponent.spy.mock.lastCall[0].status).toBe(
266+
APILoadingStatus.NOT_LOADED
267+
)
268+
);
269+
270+
await act(async () => {
271+
google.maps.Settings = {
272+
getInstance: getInstanceMock
273+
} as unknown as typeof google.maps.Settings;
274+
triggerMapsApiLoaded();
275+
});
276+
277+
await waitFor(() =>
278+
expect(ContextSpyComponent.spy.mock.lastCall[0].status).toBe(
279+
APILoadingStatus.LOADED
280+
)
281+
);
282+
expect(getInstanceMock).toHaveBeenCalled();
283+
expect(settingsInstance.fetchAppCheckToken).toBe(mockFetchToken);
284+
});
285+
247286
describe('internalUsageAttributionIds', () => {
248287
test('provides default attribution IDs in context', () => {
249288
render(

src/components/api-provider.tsx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -292,12 +292,12 @@ function useGoogleMapsApiLoader(props: APIProviderProps) {
292292

293293
// If the google.maps namespace is already available, the API has been loaded externally.
294294
if (window.google?.maps?.importLibrary as unknown) {
295-
if (!serializedApiParams) {
296-
updateLoadingStatus(APILoadingStatus.LOADED);
297-
}
298295
await Promise.all(
299296
librariesToLoad.map(name => importLibraryCallback(name))
300297
);
298+
if (!serializedApiParams) {
299+
updateLoadingStatus(APILoadingStatus.LOADED);
300+
}
301301
if (onLoad) onLoad();
302302
return;
303303
}

0 commit comments

Comments
 (0)