React Apollo Hooks使用传递空变量的突变



我试图创建一个addBook突变,但当我提交表单并调用突变时,会创建一本书,其中包含空字符串作为名称、流派和authorID。

我可以在GraphiQL中运行突变,它工作正常,所以我认为这意味着问题出在组件中。

我不知道怎么了?


突变:

const addBookMutation = gql`
mutation {
addBook(name: "", genre: "", authorID: "") {
id
name
}
}
`;

组件:

import React, { useState } from 'react';
import { useQuery, useMutation } from '@apollo/react-hooks';
import { getAuthorsQuery, addBookMutation } from '../queries/queries';
export default function AddBook() {
const { loading, error, data } = useQuery(getAuthorsQuery);
const [name, setName] = useState('');
const [genre, setGenre] = useState('');
const [authorID, setAuthorID] = useState('');
const [addBook, { data: bookData }] = useMutation(addBookMutation);
let authors = [];
if (error) return <p>Error :(</p>;
if (data) {
authors = data.authors;
}
return (
<div>
<form
className="bg-blue-900 p-4 flex flex-1 flex-wrap"
onSubmit={e => {
e.preventDefault();
addBook({
bookData: { name, genre, authorID },
});
}}
>
<label className="font-semibold text-gray-100">Book Name</label>
<input
type="text"
className="py-1 px-2 rounded border mx-2"
onChange={e => setName(e.target.value)}
/>
<label className="font-semibold text-gray-100">Genre</label>
<input
type="text"
className="py-1 px-2 rounded border mx-2"
onChange={e => setGenre(e.target.value)}
/>
<label className="font-semibold text-gray-100">Author</label>
<select
className="py-1 px-2 rounded border mx-2"
onChange={e => setAuthorID(e.target.value)}
>
{loading ? <option>Loading authors...</option> : ''}
<option defaultValue>Select Author</option>
{authors.map(author => (
<option key={author.id} value={author.id}>
{author.name}
</option>
))}
</select>
<button
type="submit"
className="bg-gray-200 text-gray-900 font-semibold py-1 px-2 rounded"
>
Add Book
</button>
</form>
</div>
);
}

首先将变量声明添加到突变

const addBookMutation = gql`
mutation AddBook($name: String!, $genre: String!, $authorID: String!){
addBook(name: $name, genre: $genre, authorID: $authorID) {
id
name
}
}
`;

然后将变量传递给声明为的突变

...
e.preventDefault();
addBook({
variables: { name, genre, authorID },
});
...

相关内容

  • 没有找到相关文章

最新更新