Mutations
The Mutation
type in your GraphQL schema contains each mutation that you can dispatch. mobx-depot
converts each
mutation into its own class.
For example, given the following schema:
input CreateUserInput { firstName: String! lastName: String! email: String! password: String!}type Mutation { createUser(input: CreateUserInput!): User}
This will generate a CreateUserMutation
class that you can use as such:
import { CreateUserMutation } from "~/models/depot";const createUser = new CreateUserMutation( // Mutation variables { input: { firstName: "John", lastName: "Doe", email: "johndoe@example.com", password: "abracadabra" } }, // Select the fields you want to retrieve user => user.name.email);createUser.dispatch().then(user => { // user is a UserModel, which is a MobX observable // It can also be null, as described by the schema});
If you want to re-use the same mutation instance, you can provide a new set of variables
when calling dispatch
:
createUser.dispatch({ input: { firstName: "Joe", lastName: "Mama", email: "joemama@example.com", password: "abracadabra" }})// ...createUser.dispatch({ input: { firstName: "Bing", lastName: "Bong", email: "bingbong@example.com", password: "abracadabra" }})
Like queries, if you don't know what the variables should be upon initialization you can provide null
in the
constructor:
const createUser = new CreateUserMutation( // We don't know what variables we want yet! null, // Select the fields you want to retrieve user => user.name.email);// ... Now we do!createUser.dispatch({ input: { firstName: "Bing", lastName: "Bong", email: "bingbong@example.com", password: "abracadabra" }})
If you call dispatch
without ever providing variables, it will throw an error at runtime.