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

[Bug fix] commerce-sdk-react hooks missing API errors #1699

Open
wants to merge 12 commits into
base: develop
Choose a base branch
from
12 changes: 11 additions & 1 deletion packages/commerce-sdk-react/src/hooks/useQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,17 @@ export const useQuery = <Client extends ApiClient, Options extends ApiOptions, D
// missing parameters. This will result in a runtime error. I think that this is an acceptable
// trade-off, as the behavior is opt-in by the end user, and it feels like adding type safety
// for this case would add significantly more complexity.
const wrappedMethod = async () => await authenticatedMethod(apiOptions as Options)
const wrappedMethod = async () => {
kevinxh marked this conversation as resolved.
Show resolved Hide resolved
try {
return await authenticatedMethod(apiOptions as Options)
} catch (e) {
if (typeof e === 'object' && e !== null && 'response' in e) {
const json = await (e.response as Response).json()
throw json
}
throw e
}
}
return useReactQuery(hookConfig.queryKey, wrappedMethod, {
enabled:
// Individual hooks can provide `enabled` checks that are done in ADDITION to
Expand Down
13 changes: 2 additions & 11 deletions packages/test-commerce-sdk-react/app/pages/query-errors.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,6 @@ const QueryErrors = () => {
// Type assertion because we're explicitly violating the expected type
const products = useProducts({parameters: {FOO: ''}} as any, {enabled: true})
const product = useProduct({parameters: {id: '25502228Mxxx'}})
/** Errors don't nicely serialize to JSON, so we have to do it ourselves. */
const toLoggable = (err: unknown) => {
if (err instanceof Error) {
// Clone all keys onto a plain object
const keys = Object.getOwnPropertyNames(err) as Array<keyof Error>
return keys.reduce((acc, key) => ({...acc, [key]: err[key]}), {})
}
return err
}

return (
<>
Expand Down Expand Up @@ -55,7 +46,7 @@ const QueryErrors = () => {
<Json
data={{
isLoading: products.isLoading,
error: toLoggable(products.error),
error: products.error,
data: products.data
}}
/>
Expand All @@ -70,7 +61,7 @@ const QueryErrors = () => {
<Json
data={{
isLoading: product.isLoading,
error: toLoggable(product.error),
error: product.error,
data: product.data
}}
/>
Expand Down
Loading