【问题标题】:Passing argument to React Apollo mutation将参数传递给 React Apollo 突变
【发布时间】:2019-10-31 21:37:00
【问题描述】:

我遇到了一个突变似乎没有发送任何参数的问题。我的突变似乎是正确的,因为我从服务器收到的错误是它没有找到用户,而不是语法问题,例如400.

export const LOGIN = gql`
    mutation signIn($email: String!, $password: String!){
        signIn(login: $email, password: $password) {
            token
        }
    }
`;

我已确认变量在本地状态下是正确的。我还确认通过 Apollo DevTools 发送凭据会返回正确的令牌。这是突变的相关位。

<Mutation
    mutation={LOGIN}
    variables={{
        email: state.auth.email,
        password: state.auth.password
    }}
    onError={(e) => {
        console.log(state.auth); // to confirm the state data is correct
        console.log(e);
    }}
    update={(store, { data }) => {
        dispatch({
            type: 'login',
            value: data.token
        })
    }}
>

在这一点上,我感到很沮丧和沮丧。任何帮助表示赞赏。

编辑 - 这似乎比我预期的要奇怪。如果我将这些值硬编码到突变的 variables 参数中,它就可以正常工作。

variables={{
    email: "some-valid-email@website.com",
    password: "some-valid-password"
}}

然而,当我通过 useContext 从 state 中传递数据时,它会中断。

const context = React.useContext(AppContext);
console.log(context.auth.email, context.auth.password); // logs the same valid email and password

【问题讨论】:

    标签: reactjs graphql apollo react-hooks


    【解决方案1】:

    这似乎是 Apollo 和 React.useContext(或 useReducer)的问题

    如果我有如下上下文:

    const context = React.useContext(AppContext);
    

    然后我将上下文(包含电子邮件/密码)传递给 GraphQL 变量,例如:

            variables={context.auth}
    

    ...它有效。

    但是单独实例化变量似乎不起作用。

    不起作用:

    let email = context.auth.email
    let password = context.auth.password
    
    variables={{email, password}}
    

    这是一个陷阱吗?我不确定。但至少我暂时有一个解决方法。

    【讨论】:

      猜你喜欢
      • 2019-10-06
      • 2018-07-15
      • 2020-09-22
      • 2023-04-03
      • 2017-03-31
      • 2018-01-27
      • 2020-05-05
      • 2017-09-22
      • 2018-06-20
      相关资源
      最近更新 更多