Search code examples
reactjstypescriptgraphqlapollo-clientredux-thunk

how can I pass arguments to the query method in apollo?


I am using apollo client to fetch the data. And I want it to only get those todos that are made by the logged in user only.

But this piece doesn't work

Source code:

import { gql } from '@apollo/client';

export const todoService = {
getTodoItems: () => gql`
    query todoQuery($loggedUserId: String!) {
      todo(where: { userId: { _eq: $loggedUserId } }, order_by: { createdAt: desc }) {
        id
        todo {
            title,
            body,
            status
        }
        userId
      }
    }
}
`

Redux thunk file

import { createAsyncThunk } from '@reduxjs/toolkit';
import { apolloClient } from '@/Apollo';
import { todoService } from './_graphql';

export const todoThunk = {
getTodoItems: createAsyncThunk(`db/getTodoItems`, async (loggedUserId: string) => {
    const response = await apolloClient.query({
      query: todoService.getTodoItems(),
      variables: { loggedUserId },
      fetchPolicy: `network-only`,
    });
    return response;
  }),

React Component

  useEffect(
     dispatch(todoThunk.getTodoItems(loggedUserId));
  ,[dispatch])

However it works when I hard code the userId in place of variable loggedUserId like this:

export const todoService = {
getTodoItems: () => gql`
    query todoQuery {
      todo(where: { userId: { _eq: "some_hard_coded_id" } }, order_by: { createdAt: desc }) {
        id
        todo {
            title,
            body,
            status
        }
        userId
      }
    }
}
`

Solution

  • this worked for me.

    import { gql } from '@apollo/client';
    
    export const todoService = {
    getTodoItems: () => gql`
        query todoQuery($loggedUserId: uuid! = loggedUserId) {
          todo(where: { userId: { _eq: $loggedUserId } }, order_by: { createdAt: desc }) {
            id
            todo {
                title,
                body,
                status
            }
            userId
          }
        }
    }
    `