在Apollo/GraphQL中,要通过mutation来修改数组。可以按如下步骤操作:
mutation AddItem($item: ItemInput!) {
addItem(item: $item) {
id
name
description
}
}
import { useMutation } from '@apollo/react-hooks';
import { ADD_ITEM } from '../graphql/mutations';
function AddItemForm() {
const [item, setItem] = useState({});
const [addItem, { loading, error }] = useMutation(ADD_ITEM, {
onCompleted(data) {
// Do something with data
},
onError(error) {
// Handle error
}
});
const handleSubmit = (e) => {
e.preventDefault();
addItem({ variables: { item } });
};
return (
)
}
const typeDefs = gql`
input ItemInput {
name: String
description: String
}
type Item {
id: Int
name: String
description: String
}
type Mutation {
addItem(item: ItemInput): Item
}
`;
const resolvers = {
Mutation: {
addItem: (_, { item }) => {
const newItem = {
id: items.length + 1,
...item
};
items.push(newItem);
return newItem;
}
}
}