You can send variables to your GraphQL queries and mutations. The variables and the type must be specified, ex: $title: String!
or $todo: todos_insert_input!
.
mutation($todo: todos_insert_input!) {
insert_todos(objects: [$todo]) {
affected_rows
}
}
Because GraphQL is strongly typed you must specify the variable types.
Here is an example using variables with the popular Apollo client.
import { gql, useMutation } from "@apollo/client";
const INSERT_TODO = gql`
mutation($todo: todos_insert_input!) {
insert_todos(objects: [$todo]) {
affected_rows
}
}
`;
function Component() {
//...
const [insertTodo] = useMutation(INSERT_TODO);
//...
return (
<form
onSubmit={async (e) => {
e.preventDefault();
try {
await insertTodo({
variables: {
todo: {
name: todoName,
},
},
});
} catch (error) {
console.error(error);
return alert("Error creating todo");
}
alert("Todo created");
setTodoName("");
}}
>
//...
</form>
);
}