GraphQL(Prisma)突变数据未定义

时间:2019-04-19 02:44:44

标签: reactjs graphql prisma

我正在尝试做一个突变,并且在React端我一直收到关于数据为空的错误。但是,如果我在GraphQL控制台中尝试相同的突变,则它可以工作。另外,我知道端点在工作,因为我可以毫无问题地查询数据。

一切

服务器代码(解析器):

 async signup(parent, args, ctx, info) {
    // lowercase their email
    args.email = args.email.toLowerCase();
    // hash their password
    const password = await bcrypt.hash(args.password, 10);
    // create the user in the database
    const user = await ctx.db.mutation.createUser({
        data: { 
          ...args,
          password,
        }
      }, info);
    return user;
}

静音(反应面)

mutation signupUser($email: String!, $password: String!, $name: String!) {
  signup(email: $email, password: $password, name: $name) {
    __typename
    id
    email
    password
    name
  }
}
TypeError: Cannot read property 'data' of undefined
    at Mutation._this.onMutationCompleted (react-apollo.esm.js:477)
    at react-apollo.esm.js:434

这也是我在组件上的突变的片段

<Mutation
        mutation={signUpUserMutation}
        onCompleted={(user) => {
          handleClose();
        }}
        onError={(error) => {
          console.log(error)
          setOpen(true);
        }}
      >
        {signup => (
          <Form
            onSubmit={async (values, { setSubmitting }) => {
              await signup({
                variables: {
                  name: values.name,
                  email: values.email,
                  password: values.password,
                },
              });
              setSubmitting(false);
            }}
          >
            {({
              values, errors, handleChange, handleBlur, isSubmitting,
            }) => (

1 个答案:

答案 0 :(得分:0)

在您的架构中

type User {
    id: Int
    name: String
    email: String
    password: String
}
type Response {
    status: Boolean
    message: String
    data: User
}
type Mutation {
    signUp(name: String!, email: String!, password: String!) : Response
}   

关于突变解析器注册功能

 async signUp(parent, args, { db }, info) {
    // lowercase their email
    args.email = args.email.toLowerCase();
    // hash their password
    const password = await bcrypt.hash(args.password, 10);
    // create the user in the database
    const data = { 
        ...args, 
        password,
    }
    const user = await db.mutation.createUser(data, info);
    return user;
 }

在数据库突变createUser函数中,您可以像这样访问

const createUser = async ({ name, email, password }, info) => {
  try {
      // Code to save user information in database
    return { status: true,
             message: "User registration successful. You can login now.", 
             data: createdUser
    }
  } catch(e) {
    return { status: false, message: e.message, data: null }
  }
}

您的查询

mutation signupUser($email: String!, $password: String!, $name: String!) {
  signup(email: $email, password: $password, name: $name) {
    status
    message
    data {
     id
     email
     password
     name
    }
  }
}