如何将参数传递给 apollo 中的查询方法?

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

我正在使用 apollo 客户端获取数据。 而且我希望它只获取那些仅由登录用户创建的待办事项。

但是这块不行

源代码:

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 文件

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 组件

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

但是,当我像这样硬编码 userId 代替变量 loggedUserId 时,它会起作用:

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
      }
    }
}
`

您似乎错过了一个 $ 标志

尝试:

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
      }
    }
}
`

这对我有用。

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
      }
    }
}
`