Skip to content

Querying custom fields

kyu edited this page Dec 8, 2022 · 2 revisions

Intro

Custom fields are an easy way to extend Vendure's built-in datatypes and store additional information for your needs. Querying them from the Shop API in the Remix storefront requires a one-time setup, which is described below.

Please note that these steps are necessary every time you wish to query new custom fields.

Prerequisites

Ensure your backend is running and that the custom fields are added.

Set the VENDURE_API_URL environment variable to your backend's Shop API URL, e.g. http://localhost:3000/shop-api.
Alternatively, hard-code the API URL by editing the codegen.yml:

overwrite: true
schema:
  - "<YOUR_API_URL>"
...

These steps are very important as we will invoke graphql-codegen to generate new datatypes from the GraphQL schema exposed by your Vendure backend.

Adding custom fields to a query

Let's assume we added a custom field weight on the product entity, which we wish to display on the product page.

First, adjust the products provider and in it the fragment that is used to query the product details:

export const detailedProductFragment = gql`
  fragment DetailedProduct on Product {
    ...
    customFields {
      weight
    }
  }
`;

On simpler queries you will find the fields directly in the referenced GraphQL query without a named fragment.
For other entities you need to modify the corresponding provider and corresponding query.

Run npm run generate afterwards. If the command succeeds, the typescript datatypes will have been updated to include the new weight field in the customFields object. You can then display it on the product page:

<h1>Product weight: {product.customFields?.weight}</h1>

Do note that individual datatypes are created per query, even if they reference the same action from the shop API. For instance, both search and searchFacetValues use Vendure's search query, but expect different data in return. If you only add a custom field to one query it will not affect the other.

Troubleshooting

Ensure you followed all steps in the prerequisites section. You can enable graphql-codegen's verbose mode in the codegen.yml if you still face issues.

Clone this wiki locally