Skip to content

Commit

Permalink
Clean up data hook.
Browse files Browse the repository at this point in the history
  • Loading branch information
allilevine committed Dec 12, 2024
1 parent 0f9de2b commit 0735e5d
Showing 1 changed file with 15 additions and 17 deletions.
32 changes: 15 additions & 17 deletions packages/data-stores/src/newsletter-categories/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,42 +15,40 @@ export type NewsletterCategories = {
newsletterCategories: NewsletterCategory[];
};

type NewsletterCategoryQueryProps = {
siteId: number;
};

type NewsletterCategoryResponse = {
enabled: boolean;
newsletter_categories: NewsletterCategory[];
};

export const getNewsletterCategoriesKey = ( siteId?: string | number ) => [
'newsletter-categories',
siteId,
];
export const getNewsletterCategoriesKey = ( siteId?: string | number ) =>
[ 'newsletter-categories', siteId ] as const; // Make tuple readonly for better caching

const convertNewsletterCategoryResponse = (
response: NewsletterCategoryResponse
): NewsletterCategories => ( {
/**
* Converts API response to correct data structure.
*/
const convertResponse = ( response: NewsletterCategoryResponse ): NewsletterCategories => ( {
enabled: response.enabled,
newsletterCategories: response.newsletter_categories,
} );

/**
* React hook to fetch newsletter categories for a site.
*/
export const useNewsletterCategories = ( {
siteId,
}: NewsletterCategoryQueryProps ): UseQueryResult< NewsletterCategories > => {
const path = `/sites/${ siteId }/newsletter-categories`;

}: {
siteId: number;
} ): UseQueryResult< NewsletterCategories > => {
return useQuery( {
queryKey: getNewsletterCategoriesKey( siteId ),
queryFn: async () => {
try {
const response = await request< NewsletterCategoryResponse >( {
path,
path: `/sites/${ siteId }/newsletter-categories`,
apiVersion: '2',
apiNamespace: 'wpcom/v2',
} );
return convertNewsletterCategoryResponse( response );
return convertResponse( response );
} catch ( e ) {
return {
enabled: false,
Expand All @@ -59,6 +57,6 @@ export const useNewsletterCategories = ( {
};
}
},
enabled: !! siteId,
enabled: Boolean( siteId ),
} );
};

0 comments on commit 0735e5d

Please sign in to comment.