DEV Community

Cover image for GraphQl with RTK Query
Oluwaseyi Komolafe
Oluwaseyi Komolafe

Posted on

1

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay