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

React Query default config and Query Key factory #707

Closed
wants to merge 9 commits into from
28 changes: 28 additions & 0 deletions packages/commerce-sdk-react/src/config/query-client.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* Copyright (c) 2022, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {DefaultOptions, QueryClientConfig} from '@tanstack/react-query'

const defaultOptions: DefaultOptions = {
queries: {
retry: 2,
refetchOnMount: 'always',
refetchOnWindowFocus: 'always',
refetchOnReconnect: 'always',
cacheTime: Infinity, //30 seconds
refetchInterval: 1000 * 30, //30 seconds
refetchIntervalInBackground: false,
suspense: false,
staleTime: 1000 * 30
},
mutations: {
retry: 2
}
}

const defaultQueryClientConfig: QueryClientConfig = {defaultOptions}

export {defaultQueryClientConfig}
29 changes: 25 additions & 4 deletions packages/commerce-sdk-react/src/hooks/ShopperProducts/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,24 @@ import {UseQueryOptions, UseQueryResult} from '@tanstack/react-query'

type Client = ApiClients['shopperProducts']

const productKeys = {
all: [{entity: 'product'}],
useProducts: (arg: Record<string, unknown>) => [{...productKeys.all[0], scope: 'list', ...arg}],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the reason for having the query key to be structured as an array of 1 item (which is an object)?

According to the official doc, it's possible to mix and match the array's content. For example, it can be like:
['product', 'list', {...arg}]

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we use a multiple-items array as the query key, we can easily invalidate the queries granularly like this:

queryClient.invalidateQueries(['product']) // will invalidate both `useProduct` and `useProducts`
queryClient.invalidateQueries(['product', 'list']) // will invalidate only `useProducts`

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason comes from a TkDodo's blog post: https://tkdodo.eu/blog/leveraging-the-query-function-context#object-query-keys

The author proposes to define all keys as an array with exactly one object.

The object inside the key contains the query data returned and some high-level strings we use to define the 'entity' and 'scope' ideas.

Using an object we don't need o to worry about the specific position of a particular key in the array. Instead, we can obtain the value of a particular key by using the object name destructuring.

And we can still use fuzzy matching query keys when we need to invalidate related queries during mutations.

useProduct: (arg: Record<string, unknown>) => [
{...productKeys.all[0], scope: 'detail', ...arg},
],
}

const categoryKeys = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps we can make a factory function that allows us to easily generate productKeys and categoryKeys. And calling it would be like this:

const categoryKeys = createQueryKeys('category', {useCategories: 'list', useCategory: 'detail'})
const productKeys = createQueryKeys('product', {useProducts: 'list', useProduct: 'detail'})

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is the idea of the new NPM package @lukemorales/query-key-factory recently linked from the React Query docs: https://tanstack.com/query/v4/docs/guides/query-keys

I've been testing the package, but so far I see the package is not compatible with the idea mentioned in the previous comment of defining all keys as an array with exactly one object.

all: [{entity: 'category'}],
useCategories: (arg: Record<string, unknown>) => [
{...categoryKeys.all[0], scope: 'list', ...arg},
],
useCategory: (arg: Record<string, unknown>) => [
{...categoryKeys.all[0], scope: 'detail', ...arg},
],
}

type UseProductsParameters = NonNullable<Argument<Client['getProducts']>>['parameters']
type UseProductsHeaders = NonNullable<Argument<Client['getProducts']>>['headers']
type UseProductsArg = {headers?: UseProductsHeaders; rawResponse?: boolean} & UseProductsParameters
Expand Down Expand Up @@ -39,7 +57,10 @@ function useProducts(
const {shopperProducts: client} = useCommerceApi()
const {headers, rawResponse, ...parameters} = arg
return useAsync(
['products', arg],
// Query Key needs to match "options"
// ['products', {headers, rawResponse, ...parameters}],
productKeys.useProducts(arg),
// Don't send "options" different from the queryKey
() => client.getProducts({parameters, headers}, rawResponse),
options
)
Expand Down Expand Up @@ -73,7 +94,7 @@ function useProduct(
const {headers, rawResponse, ...parameters} = arg
const {shopperProducts: client} = useCommerceApi()
return useAsync(
['product', arg],
productKeys.useProduct(arg),
() => client.getProduct({parameters, headers}, rawResponse),
options
)
Expand Down Expand Up @@ -111,7 +132,7 @@ function useCategories(

const {shopperProducts: client} = useCommerceApi()
return useAsync(
['categories', arg],
categoryKeys.useCategories(arg),
() => client.getCategories({parameters, headers}, rawResponse),
options
)
Expand Down Expand Up @@ -148,7 +169,7 @@ function useCategory(

const {shopperProducts: client} = useCommerceApi()
return useAsync(
['category', arg],
categoryKeys.useCategory(arg),
() => client.getCategory({parameters, headers}, rawResponse),
options
)
Expand Down
4 changes: 3 additions & 1 deletion packages/commerce-sdk-react/src/hooks/useAsync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ export const useAsync = <T>(
fn: () => Promise<T>,
queryOptions?: UseQueryOptions<T, Error>
) => {
// add more logic in here
// React Query uses QueryFunctionContext object to inject information about
// the query to the queryFn.
// fn will receive {queryKey} as a parameter
return useQuery<T, Error>(queryKey, fn, queryOptions)
}

Expand Down
11 changes: 10 additions & 1 deletion packages/commerce-sdk-react/src/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {

import {ApiClientConfigParams, ApiClients} from './hooks/types'
import {QueryClient, QueryClientConfig, QueryClientProvider} from '@tanstack/react-query'
import {defaultQueryClientConfig} from './config/query-client.config'
import {ReactQueryDevtools} from '@tanstack/react-query-devtools'

export interface CommerceApiProviderProps extends ApiClientConfigParams {
Expand All @@ -42,7 +43,15 @@ export const CommerceApiContext = React.createContext({} as ApiClients)
* @returns Provider to wrap your app with
*/
const CommerceApiProvider = (props: CommerceApiProviderProps): ReactElement => {
const {children, clientId, organizationId, shortCode, siteId, proxy, queryClientConfig} = props
const {
children,
clientId,
organizationId,
shortCode,
siteId,
proxy,
queryClientConfig = defaultQueryClientConfig
} = props

// DEBUG: copy access token from browser
const headers = {
Expand Down