DEV Community

Cover image for GraphQl with RTK Query
Oluwaseyi Komolafe
Oluwaseyi Komolafe

Posted on

GraphQl with RTK Query

I am a huge fan of the RTKQuery and how it works with the fetchBaseQuery for calling REST APIs but the beauty of it is that it can work quite the same way for GraphQl endpoints as well. But sadly the documentation on the Redux Toolkit documentation is not broad enough, at least in the aspect of mutations.

So i think i can help with that - both queries and mutations.

Now, right into it, let's say we have our project setup and we have the services for a blog post set up to getBlogPosts from a graphql endpoint.

import {  createApi } from '@reduxjs/toolkit/query/react'
import { gql } from 'graphql-request'
import {graphqlRequestBaseQuery} from '@rtk-query/graphql-request-base-query'

export const postStatuses = ['draft', 'published', 'pending_review'] as const

export interface Post {
  id: string
  title: string
  author: string
  content: string
  status: typeof postStatuses[number]
  created_at: string
  updated_at: string
}

export interface Pagination {
  page: number
  per_page: number
  total: number
  total_pages: number
}

export interface GetPostsResponse extends Pagination {
  data: {
    posts: Post[]
  }
}

export const api = createApi({
  baseQuery: graphqlRequestBaseQuery({
    url: '/graphql',
  }),
  endpoints: (builder) => ({
    getPosts: builder.query<
      GetPostsResponse,
      { page?: number; per_page?: number }
    >({
      query: ({ page, per_page }) => ({
        document: gql`
          query GetPosts($page: Int = 1, $per_page: Int = 10){
            posts(page: $page, per_page: $per_page) {
              id
              title
            }
          }
        `,
        variables: {
          page,
          per_page,
        },
      }),
    }),
  }),
})
export const { useGetPostsQuery } = api
Enter fullscreen mode Exit fullscreen mode

Now to post a blog, i.e. make a mutation we will need to further add another block of code.

   addPost: builder.mutation<any, any>({
      query: ({id, title, content}) => ({
        document: gql`
          mutation addPost($id: Int!, $title: String!, content: String!) {
            addPost(id: $id, title: $title, content: $content)
          }
        `,
        variables: {
          id,
          title,
          content,
        },
      }),
    }),

...
...
export const { useGetPostsQuery, useAddPostMutation } = api
Enter fullscreen mode Exit fullscreen mode

and the same can work for deleting posts and whatever mutations we need to make.

I hope this helps someone that needs it, I would also like to know what alternatives you use in calling your graphql APIs.

Top comments (0)