Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use fetch instead of apiFetch. #9936

Merged
merged 10 commits into from
Jan 6, 2025
18 changes: 8 additions & 10 deletions assets/js/hooks/useMonitorInternetConnection.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,18 +53,16 @@ export function useMonitorInternetConnection() {
}

try {
const connectionCheckResponse = await apiFetch( {
path: '/google-site-kit/v1/',
} );

// We are only interested if the request was successful, to
// confirm online status.
const canReachConnectionCheck = !! connectionCheckResponse;

setIsOnline( canReachConnectionCheck );
await apiFetch( { path: '/google-site-kit/v1/' } );
} catch ( err ) {
setIsOnline( false );
if ( err?.code === 'fetch_error' ) {
setIsOnline( false );
return;
}
}
// If the request succeeded or failed for any other reason,
// we should still be online.
setIsOnline( true );
}, [ setIsOnline ] );

useLifecycles(
Expand Down
17 changes: 17 additions & 0 deletions assets/js/hooks/useMonitorInternetConnection.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,4 +177,21 @@ describe( 'useMonitorInternetConnection', () => {

expect( fetchMock ).toHaveFetchedTimes( 1 );
} );

it( 'should set offline status when a fetch_error occurs', async () => {
fetchMock.getOnce( connectionCheckEndpoint, {
throws: { code: 'fetch_error' },
} );

renderHook( () => useMonitorInternetConnection(), { registry } );
mockOnlineStatus( true );

await act( async () => {
global.window.dispatchEvent( new Event( 'online' ) );
await waitForTimeouts( 100 );
} );

expect( store.getState().isOnline ).toBe( false );
expect( fetchMock ).toHaveFetched( connectionCheckEndpoint );
} );
} );
Loading