Use RTK Query with Graphql

Viewed 4016

So far I understand I need to build my own baseQuery. I could write graphql queries and mutations like in example here https://rtk-query-docs.netlify.app/examples/react-with-graphql, will I get full type safety for queries and mutations if I add types to query.builder like this builder.query<Device, void> or I must use something like this https://www.graphql-code-generator.com/docs/plugins/typescript-graphql-request#simple-request-middleware. In latter case how should my baseQuery look if I use generated hook for graphql-request library.

Here is example of hook from 2:

import { GraphQLClient } from 'graphql-request';
import { getSdk } from './sdk'; // THIS FILE IS THE GENERATED FILE
async function main() {
  const client = new GraphQLClient('https://countries.trevorblades.com/');
  const sdk = getSdk(client);
  const { continents } = await sdk.continents(); // This is fully typed, based on the query
  console.log(`GraphQL data:`, continents);
}

I am thinking something like:

    import {getSdk} from './sdk'
    const client = new GraphQLClient('https://countries.trevorblades.com/');
    const graphqlBaseQuery = (someGeneratedQueryOrMutation, client) => {
      const something = someGeneratedQueryOrMutation(client);
      const { continents } = await something.continents();
      return { data: continents };
    };

Code does not really make sence but I hope you see where I am going with this. Thanks :)

1 Answers

Edit: By now there is a Grahql Codegen plugin available at https://www.graphql-code-generator.com/docs/plugins/typescript-rtk-query


Actually I started writing a plugin for the code generator a few days ago. You can see the generated result here: https://github.com/phryneas/graphql-code-generator/blob/5f9a2eefd81538782b791e0cc5df633935164a89/dev-test/githunt/types.rtk-query.ts#L406-L427

This would require you to create an api with a baseQuery using a graphql library of your choice like this.

A configuration would look like this

  ./dev-test/githunt/types.rtk-query.ts:
    schema: ./dev-test/githunt/schema.json
    documents: ./dev-test/githunt/**/*.graphql
    plugins:
      - typescript
      - typescript-operations
      - typescript-rtk-query
    config:
      importBaseApiFrom: '../../packages/plugins/typescript/rtk-query/tests/baseApi'
      exportHooks: true

And I think for bundle-splitting purposes it would also work with the near-operation-file preset.

All that is not upstream yet - I will try to get that ready this weekend but don't know how much time it would take to actually get it in.

You could check the repo out, do a local build and install it with something like yalc though.

For a more basic approach without code generation you could look at this example or for an a bit more advanced setup (but also without full code generation, more integrated with existing tooling) you could look at this PR

Related