【问题标题】:how can I pass arguments to the query method in apollo?如何将参数传递给 apollo 中的查询方法?
【发布时间】:2021-12-30 12:00:18
【问题描述】:

我正在使用 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;
  }),

反应组件

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

【问题讨论】:

  • todo(where: { userId: { _eq: $loggedUserId ..... 编码前在操场上测试查询(使用变量)
  • 使用变量测试过?显示它
  • 我在 hasura api 中对其进行了测试,但没有使用变量我在那里运行此查询并且它可以工作 todo(where: { userId: { _eq: 'id_here' }}
  • 再次,使用变量进行测试

标签: reactjs typescript graphql apollo-client redux-thunk


【解决方案1】:

您似乎错过了$ 标志

尝试:

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

【讨论】:

  • 抱歉打错了。添加 $ 符号后它也不起作用
【解决方案2】:

这对我有用。

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

【讨论】:

    猜你喜欢
    • 2019-04-15
    • 2019-04-02
    • 2018-09-30
    • 2017-03-08
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    相关资源
    最近更新 更多