【发布时间】:2021-09-05 02:01:26
【问题描述】:
我对@987654321@ 很陌生。话不多说,上代码。我有一个正在运行的服务器,我正在尝试使用 react 进行突变。
server.js中的突变
const RootMutationType = new GraphQLObjectType({
name: "RootMutation",
description: "Root Mutation Type.",
fields: () => ({
addBook: {
type: BookType,
args: {
authorId: { type: GraphQLID },
name: { type: GraphQLString },
},
resolve: async (parent, args) => {
const book = new Book({
name: args.name,
authorId: args.authorId,
});
return await book.save();
},
},
......
// other crazy stuff here
使用graphiql 我可以添加一本书,这意味着服务器运行良好。但是在反应客户端上,当我尝试添加一本书时,我得到了错误。这是我所拥有的。
mutations.js
import { gql } from "@apollo/client";
const ADD_BOOK_MUTATION = gql`
mutation addBook($authorId: Integer!, $name: String!) {
addBook(authorId: $authorId, name: $name) {
name
id
}
}
`;
export { ADD_BOOK_MUTATION };
Form.jsx
import React, { useEffect, useRef } from "react";
import { useMutation } from "@apollo/client";
import { ADD_BOOK_MUTATION } from "./mutations";
const Index = () => {
const [addBook, { data, error }] = useMutation(ADD_BOOK_MUTATION);
const idRef = useRef(null);
const nameRef = useRef(null);
useEffect(() => {
if (error) {
console.error(error);
} else {
console.log(data);
}
}, [data, error]);
const addBookHandler = (e) => {
e.preventDefault();
addBook({
variables: {
authorId: idRef.current.value,
name: nameRef.current.value,
},
});
};
return (
<form className="form">
<input ref={idRef} type="number" placeholder="author id" />
<input ref={nameRef} type="text" placeholder="book name" />
<button onClick={addBookHandler}>addBook</button>
</form>
);
};
export default Index;
谁能告诉我我哪里错了!!帮助输入将不胜感激!
【问题讨论】:
标签: javascript reactjs graphql apollo-client react-apollo