dotansimha / dotansimha/graphql-code-generator-community
[Documentation] useMutation example for Vue Composition API
- Dominant language
- TypeScript
- Stars
- 137
- Forks
- 195
- Avg merge
- 6h 20m
- Merged PRs (30d)
- 16
Description
**Describe the bug**
Currently there's no example on how to use the `useUpdateBooksMutation` or something similar in the [docs](https://graphql-code-generator.com/docs/plugins/typescript-vue-apollo#usage-examples). It would be great if someone with knowledge could provide a simple example where `loading`, `error` `onDone` and `mutation` are used.
**Additional context**
Consider this mutation:
```
mutation {
setViewerPreference(options: { language: "bb-bb" }) {
language
}
}
```
For this to work I created a file called `setLanguage.graphql` for graphql-codegen (a full options object as used in the Playground would've been better but I don't have that skill yet):
```typescript
mutation setLanguage($language: String!) {
setViewerPreference(options: { language: $language }) {
language
}
}
```
Using this in a component in `Settings.vue` looks like this:
```typescript
import { defineComponent, ref, watch } from '@vue/composition-api'
import { useSetLanguageMutation } from 'src/graphql/generated/operations'
export default defineComponent({
setup(_, context) {
const languageOptions = [
{ value: 'en-us', label: 'English' },
{ value: 'nl-be', label: 'Nederlands' },
]
const language = ref(context.root.$i18n.locale)
const { mutate, loading, error, onDone } = useSetLanguageMutation({
variables: {
language: 'ee-ee',
},
})
watch(language, (newLanguage) => {
context.root.$i18n.locale = newLanguage
void mutate({ language: newLanguage })
})
return { language, languageOptions, }
},
})
```
### Questions/unclear
I don't understand why the function `useSetLanguageMutation` needs to be initialized with a `variables` value already? It would be great if one could just do this:
```typescript
const { mutate, loading, error, onDone } = useSetLanguageMutation()
watch(language, (newLanguage) => {
void mutate({ language: newLanguage })
})
```
On a side note, when calling the `mutate()` function, the one that really executes the mutation, are the `loading` and other `const` returned by `useSetLanguageMutation` still usable?
I'm sorry for these stupid questions, but as you can see I'm a noob and would love to have a more detailed example or at least one example on how to properly use the `useMutation` generated by the graphql codegen. It would even be better if it would include an example on how to update the cache too, but this is of course out of scope for the codegen. I tried to follow [this example](https://www.youtube.com/watch?v=lQ7t20gFR14&feature=youtu.be) but it's for react.
Thank you anyhow for reading this far.
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.