Skip to content

Commit

Permalink
Refactor to use React Query in the command palette
Browse files Browse the repository at this point in the history
  • Loading branch information
danielbachhuber committed Jan 4, 2024
1 parent 3af05de commit 4669612
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 78 deletions.
59 changes: 30 additions & 29 deletions client/data/hosting/use-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,15 @@ export const USE_EDGE_CACHE_QUERY_KEY = 'edge-cache-key';
export const TOGGLE_EDGE_CACHE_MUTATION_KEY = 'set-edge-site-mutation-key';
export const CLEAR_EDGE_CACHE_MUTATION_KEY = 'clear-edge-site-mutation-key';

interface MutationVariables {
interface ClearEdgeCacheMutationVariables {
name: string;
}

interface SetEdgeCacheMutationVariables {
siteId: number;
active: boolean;
}

interface MutationResponse {
message: string;
}
Expand All @@ -35,17 +40,6 @@ export const getEdgeCacheStatus = async ( siteId: number ) => {
return response;
};

export const setEdgeCache = async ( siteId: number, newStatus: boolean ) => {
const response = await wp.req.post( {
path: `/sites/${ siteId }/hosting/edge-cache/active`,
apiNamespace: 'wpcom/v2',
body: {
active: newStatus,
},
} );
return response;
};

export const purgeEdgeCache = async ( siteId: number ) => {
return await wp.req.post( {
path: `/sites/${ siteId }/hosting/edge-cache/purge`,
Expand Down Expand Up @@ -73,28 +67,33 @@ interface MutationError {
}

export const useSetEdgeCacheMutation = (
siteId: number,
options: UseMutationOptions< boolean, MutationError, boolean > = {}
options: UseMutationOptions< boolean, MutationError, SetEdgeCacheMutationVariables > = {}
) => {
const queryClient = useQueryClient();
const mutation = useMutation< boolean, MutationError, boolean >( {
mutationFn: async ( active ) => {
return setEdgeCache( siteId, active );
const mutation = useMutation< boolean, MutationError, SetEdgeCacheMutationVariables >( {
mutationFn: async ( { active, siteId } ) => {
return await wp.req.post( {
path: `/sites/${ siteId }/hosting/edge-cache/active`,
apiNamespace: 'wpcom/v2',
body: {
active,
},
} );
},
mutationKey: [ TOGGLE_EDGE_CACHE_MUTATION_KEY, siteId ],
onMutate: async ( active ) => {
onMutate: async ( { active, siteId } ) => {
await queryClient.cancelQueries( {
queryKey: [ USE_EDGE_CACHE_QUERY_KEY, siteId ],
} );
const previousData = queryClient.getQueryData( [ USE_EDGE_CACHE_QUERY_KEY, siteId ] );
queryClient.setQueryData( [ USE_EDGE_CACHE_QUERY_KEY, siteId ], active );
return previousData;
},
onError( _err, _newActive, prevValue ) {
onError( _err, { siteId }, prevValue ) {
// Revert to previous settings on failure
queryClient.setQueryData( [ USE_EDGE_CACHE_QUERY_KEY, siteId ], Boolean( prevValue ) );
},
onSettled: ( ...args ) => {
const { siteId } = args[ 2 ];
// Refetch settings regardless
queryClient.invalidateQueries( {
queryKey: [ USE_EDGE_CACHE_QUERY_KEY, siteId ],
Expand All @@ -103,21 +102,23 @@ export const useSetEdgeCacheMutation = (
},
} );

const { mutate } = mutation;
// isMutating is returning a number. Greater than 0 means we have some pending mutations for
// the provided key. This is preserved across different pages, while isLoading it's not.
// TODO: Remove that when react-query v5 is out. They seem to have added isPending variable for this.
const isLoading =
useIsMutating( { mutationKey: [ TOGGLE_EDGE_CACHE_MUTATION_KEY, siteId ] } ) > 0;
const { mutate, ...rest } = mutation;

const setEdgeCacheCallback = useCallback( mutate, [ mutate ] );
const setEdgeCache = useCallback(
( siteId: number, active: boolean ) => mutate( { siteId, active } ),
[ mutate ]
);

return { setEdgeCache: setEdgeCacheCallback, isLoading };
return { setEdgeCache, ...rest };
};

export const useClearEdgeCacheMutation = (
siteId: number,
options: UseMutationOptions< MutationResponse, MutationError, MutationVariables > = {}
options: UseMutationOptions<
MutationResponse,
MutationError,
ClearEdgeCacheMutationVariables
> = {}
) => {
const mutation = useMutation( {
mutationFn: async () => purgeEdgeCache( siteId ),
Expand Down
15 changes: 10 additions & 5 deletions client/my-sites/hosting/cache-card/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,9 @@ export const CacheCard = ( {

const isEdgeCacheEligible = ! isPrivate && ! isComingSoon;

const { setEdgeCache, isLoading: toggleEdgeCacheLoading } = useSetEdgeCacheMutation( siteId, {
const { setEdgeCache, isLoading: isEdgeCacheMutating } = useSetEdgeCacheMutation( {
onSettled: ( ...args ) => {
const active = args[ 2 ];
const active = args[ 2 ].active;
recordTracksEvent(
active
? 'calypso_hosting_configuration_edge_cache_enable'
Expand Down Expand Up @@ -130,7 +130,7 @@ export const CacheCard = ( {
isClearingCache ||
shouldRateLimitCacheClear ||
getEdgeCacheLoading ||
toggleEdgeCacheLoading
isEdgeCacheMutating
}
>
<span>{ translate( 'Clear cache' ) }</span>
Expand Down Expand Up @@ -182,7 +182,12 @@ export const CacheCard = ( {
<>
<ToggleLabel>{ translate( 'Global edge cache' ) }</ToggleLabel>
<ToggleControl
disabled={ clearEdgeCacheLoading || getEdgeCacheLoading || ! isEdgeCacheEligible }
disabled={
clearEdgeCacheLoading ||
getEdgeCacheLoading ||
! isEdgeCacheEligible ||
isEdgeCacheMutating
}
checked={ isEdgeCacheActive }
onChange={ ( active ) => {
dispatch(
Expand All @@ -194,7 +199,7 @@ export const CacheCard = ( {
{ duration: 5000, id: EDGE_CACHE_ENABLE_DISABLE_NOTICE_ID }
)
);
setEdgeCache( active );
setEdgeCache( siteId, active );
} }
label={ edgeCacheToggleDescription }
/>
Expand Down
2 changes: 1 addition & 1 deletion client/my-sites/hosting/cache-card/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ describe( 'CacheCard component', () => {
expect( useSetEdgeCacheMutation().setEdgeCache ).not.toHaveBeenCalled();
expect( screen.getByRole( 'checkbox' ) ).toBeVisible();
screen.getByRole( 'checkbox' ).click();
expect( useSetEdgeCacheMutation().setEdgeCache ).toHaveBeenCalledWith( true );
expect( useSetEdgeCacheMutation().setEdgeCache ).toHaveBeenCalledWith( 1, true );
} );
it( 'displays rate limit message when shouldRateLimitCacheClear prop is true', () => {
useEdgeCacheQuery.mockReturnValue( { data: false, isLoading: false } );
Expand Down
68 changes: 25 additions & 43 deletions client/sites-dashboard/components/wpcom-smp-commands.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Gridicon, JetpackLogo } from '@automattic/components';
import { HELP_CENTER_STORE } from '@automattic/help-center/src/stores';
import { useQueryClient } from '@tanstack/react-query';
import { useDispatch as useDataStoreDispatch } from '@wordpress/data';
import {
alignJustify as acitvityLogIcon,
Expand Down Expand Up @@ -37,9 +36,8 @@ import WooCommerceLogo from 'calypso/components/woocommerce-logo';
import {
EDGE_CACHE_ENABLE_DISABLE_NOTICE_ID,
getEdgeCacheStatus,
setEdgeCache,
useSetEdgeCacheMutation,
purgeEdgeCache,
USE_EDGE_CACHE_QUERY_KEY,
} from 'calypso/data/hosting/use-cache';
import { SiteExcerptData } from 'calypso/data/sites/site-excerpt-types';
import { navigate } from 'calypso/lib/navigate';
Expand Down Expand Up @@ -94,9 +92,21 @@ export const useCommandsArrayWpcom = ( {
};

const commandNavigation = useCommandNavigation();
const queryClient = useQueryClient();

const dispatch = useDispatch();

const { setEdgeCache } = useSetEdgeCacheMutation( {
onSettled: ( ...args ) => {
const { active } = args[ 2 ];
dispatch(
createNotice(
'is-success',
active ? __( 'Edge cache enabled.' ) : __( 'Edge cache disabled.' ),
{ duration: 5000, id: EDGE_CACHE_ENABLE_DISABLE_NOTICE_ID }
)
);
},
} );

const displayNotice = (
message: string,
noticeType: NoticeStatus = 'is-success',
Expand Down Expand Up @@ -242,25 +252,11 @@ export const useCommandsArrayWpcom = ( {
return;
}

const { removeNotice: removeLoadingNotice } = displayNotice(
__( 'Enabling edge cache…' ),
'is-plain',
5000,
{ id: EDGE_CACHE_ENABLE_DISABLE_NOTICE_ID }
);
try {
await setEdgeCache( siteId, true );
queryClient.setQueryData( [ USE_EDGE_CACHE_QUERY_KEY, siteId ], true );
removeLoadingNotice();
displayNotice( __( 'Edge cache enabled.' ), 'is-success', 5000, {
id: EDGE_CACHE_ENABLE_DISABLE_NOTICE_ID,
} );
} catch ( error ) {
removeLoadingNotice();
displayNotice( __( 'Failed to enable edge cache.' ), 'is-error', 5000, {
id: EDGE_CACHE_ENABLE_DISABLE_NOTICE_ID,
} );
}
displayNotice( __( 'Enabling edge cache…' ), 'is-plain', 5000, {
id: EDGE_CACHE_ENABLE_DISABLE_NOTICE_ID,
} );

setEdgeCache( siteId, true );
};

const disableEdgeCache = async ( siteId: number ) => {
Expand All @@ -273,25 +269,11 @@ export const useCommandsArrayWpcom = ( {
return;
}

const { removeNotice: removeLoadingNotice } = displayNotice(
__( 'Disabling edge cache…' ),
'is-plain',
5000,
{ id: EDGE_CACHE_ENABLE_DISABLE_NOTICE_ID }
);
try {
await setEdgeCache( siteId, false );
queryClient.setQueryData( [ USE_EDGE_CACHE_QUERY_KEY, siteId ], false );
removeLoadingNotice();
displayNotice( __( 'Edge cache disabled.' ), 'is-success', 5000, {
id: EDGE_CACHE_ENABLE_DISABLE_NOTICE_ID,
} );
} catch ( error ) {
removeLoadingNotice();
displayNotice( __( 'Failed to disable edge cache.' ), 'is-error', 5000, {
id: EDGE_CACHE_ENABLE_DISABLE_NOTICE_ID,
} );
}
displayNotice( __( 'Disablingq edge cache…' ), 'is-plain', 5000, {
id: EDGE_CACHE_ENABLE_DISABLE_NOTICE_ID,
} );

setEdgeCache( siteId, false );
};

const { openPhpMyAdmin } = useOpenPhpMyAdmin();
Expand Down

0 comments on commit 4669612

Please sign in to comment.