-
Notifications
You must be signed in to change notification settings - Fork 264
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
Fetching data docs (rfc) #324
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,234 @@ | ||
# Fetching data in Hydrogen | ||
|
||
Hydrogen provides utilities to send GraphQL queries and mutations to the Storefront API. | ||
|
||
## Creating and injecting the storefront client | ||
|
||
First of all, it's necessary to create and inject the Hydrogen `storefront` client into the loader context in Remix. In the server/worker entry file, call `createStorefrontClient` inside `getLoadContext`: | ||
|
||
```ts | ||
import {createStorefrontClient} from '@shopify/hydrogen'; | ||
import {createRequestHandler, getBuyerIp} from '@remix-run/oxygen'; | ||
|
||
export default { | ||
async fetch(request: Request, env: Env, executionContext: ExecutionContext) { | ||
const cache = await caches.open('hydrogen'); | ||
|
||
const handleRequest = createRequestHandler({ | ||
build: remixBuild, | ||
mode: process.env.NODE_ENV, | ||
getLoadContext() { | ||
const {storefront} = createStorefrontClient({ | ||
cache, | ||
waitUntil: (p: Promise) => executionContext.waitUntil(p), | ||
buyerIp: getBuyerIp(request), | ||
publicStorefrontToken: env.SHOPIFY_STOREFRONT_API_PUBLIC_TOKEN, | ||
storefrontApiVersion: env.SHOPIFY_STOREFRONT_API_VERSION, | ||
storeDomain: env.SHOPIFY_STORE_DOMAIN, | ||
}); | ||
|
||
return {storefront}; | ||
}, | ||
}); | ||
|
||
return handleRequest(request); | ||
}, | ||
}; | ||
``` | ||
|
||
## Running queries | ||
|
||
To load data into your Hydrogen app, use a Remix `loader` and write a GraphQL query. Hydrogen provides a special `storefront` param to make queries against your Shopify storefront. | ||
|
||
```ts | ||
import type {ProductType} from '@shopify/hydrogen-react/storefront-api-types'; | ||
import {json, useLoaderData, type LoaderArgs} from '@remix-run/oxygen'; | ||
|
||
export async function loader({params, context: {storefront}}: LoaderArgs) { | ||
const productQuery = storefront.query<ProductType>( | ||
`#graphql | ||
query Product($handle: String!) { | ||
product(handle: $handle) { | ||
id | ||
title | ||
} | ||
} | ||
`, | ||
{ | ||
/** | ||
* Pass variables related to the query. | ||
*/ | ||
variables: { | ||
handle: params.handle, | ||
}, | ||
/** | ||
* Cache your server-side query with a built-in best practice default (SWR). | ||
*/ | ||
cache: storefront.CacheShort(), | ||
}, | ||
); | ||
|
||
return json({ | ||
product: await productQuery, | ||
}); | ||
} | ||
|
||
export default function Product() { | ||
const {product} = useLoaderData<typeof loader>(); | ||
|
||
// ... | ||
} | ||
``` | ||
|
||
Sometimes, you will want to prioritize critical data, like product information, while deferring comments or reviews. | ||
|
||
```ts | ||
import {defer, useLoaderData, type LoaderArgs} from '@remix-run/oxygen'; | ||
|
||
export async function loader({params, context: {storefront}}: LoaderArgs) { | ||
const productQuery = storefront.query( | ||
`#graphql | ||
query Product($handle: String!) { | ||
product(handle: $handle) { | ||
id | ||
title | ||
} | ||
} | ||
`, | ||
{ | ||
variables: { | ||
handle: params.handle, | ||
}, | ||
}, | ||
); | ||
|
||
const reviewsQuery = storefront.query( | ||
`#graphql | ||
query ProductReviews($handle: String!) { | ||
productReviews(handle: $handle) { | ||
nodes { | ||
description | ||
} | ||
} | ||
} | ||
`, | ||
{ | ||
variables: { | ||
handle: params.handle, | ||
}, | ||
}, | ||
); | ||
|
||
return defer({ | ||
product: await productQuery, | ||
reviews: reviewsQuery, | ||
}); | ||
} | ||
|
||
export default PageComponent() { | ||
const {product, reviews} = useLoaderData<typeof loader>(); | ||
|
||
return ( | ||
<div> | ||
<Product value={product} /> | ||
<Suspense fallback={<Spinner />}> | ||
<Await resolve={reviews}> | ||
{({productReviews}) => <ProductReviews value={productReviews.nodes}>} | ||
</Await> | ||
</Suspense> | ||
</div> | ||
); | ||
} | ||
``` | ||
|
||
### Caching data | ||
|
||
Data that is not updated often can be cached to speed up subsequent queries. Hydrogen supports caching at the sub-request level: | ||
|
||
```tsx | ||
import {defer, type LoaderArgs} from '@remix-run/oxygen'; | ||
|
||
export async function loader({params, context: {storefront}}: LoaderArgs) { | ||
const productQuery = storefront.query( | ||
`#graphql | ||
query Product($handle: String!) { | ||
product(handle: $handle) { | ||
id | ||
title | ||
} | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe a better example of something you wouldn't want to cache would be cart? Realistically I would think product id and title would be cached for long. |
||
`, | ||
{ | ||
variables: { | ||
handle: params.handle, | ||
}, | ||
cache: storefront.CacheLong(), | ||
}, | ||
); | ||
|
||
const reviewsQuery = storefront.query( | ||
`#graphql | ||
query ProductReviews($handle: String!) { | ||
productReviews(handle: $handle) { | ||
nodes { | ||
description | ||
} | ||
} | ||
} | ||
`, | ||
{ | ||
variables: { | ||
handle: params.handle, | ||
}, | ||
cache: storefront.CacheShort(), | ||
}, | ||
); | ||
|
||
return defer({ | ||
product: await productQuery, | ||
reviews: reviewsQuery, | ||
}); | ||
} | ||
``` | ||
|
||
By default, Hydrogen adds the equivalent to `storefront.CacheShort()` to every query. Sometimes, when data can be mutated by the user in the same page, you may want to disable caching manually by passing `storefront.cacheNone()`. This will prevent serving stale data when Remix refreshes the loaders after a mutation. | ||
|
||
## Mutating data | ||
|
||
To mutate data in actions, use the `storefront.mutate` function. This is just like the `query` property, except caching is disabled: | ||
|
||
```ts | ||
export async function action({request, context: {storefront}}) { | ||
const formData = await request.formData(); | ||
|
||
const cartMutation = storefront.mutate( | ||
`#graphql | ||
mutation lineItemUpdate($lineId: ID!, $input: CartLineUpdateInput!) { | ||
lineItemUpdate(lineId: $lineId, input: $input) { | ||
quantity | ||
} | ||
} | ||
`, | ||
{ | ||
/** | ||
* Pass variables related to the query. | ||
*/ | ||
variables: { | ||
lineId: formData.get('lineId'), | ||
input: formData.get('input'), | ||
}, | ||
/** | ||
* Mutations are NEVER cached by default. | ||
*/ | ||
}, | ||
); | ||
|
||
return json({ | ||
status: 'ok', | ||
}); | ||
} | ||
``` | ||
|
||
## Injecting country and language directives into queries | ||
|
||
The Storefront API accepts an [`@inContext` directive](https://shopify.dev/custom-storefronts/internationalization/international-pricing) to support international pricing. Whereas you can pass variables directly when calling `storefront.query`, it's also possible to inject the `language` and `country` variables automatically. To enable this feature, check how to use the `i18n` property when creating the Storefront client in the [i18n documentation](./i18n.md). |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should this example also include how to consume the deferred data from
useLoaderData()
?