How Do I Chain Usequery And Usemutation In Graphql Properly?
I have useQuery and useMutation from react-apollo-hooks back to back. I want to be able to use the returned values from useQuery as variables for useMutation. Currently, the valu
Solution 1:
How do I make sure that the returned value is defined in time?
You can simply check condition after useQuery
block
UPDATE
Hooks can't be called conditionally.
Usual advice is to place condition in useEffect
:
const { data, error, loading } = useQuery(GET_POSTS, {
variables: {
id: props.match.params.id
}
})
const item = props.match.params.id
// data.posts can be undefined at startconst owner = loading ? null : data.posts[0].author.id
const variables = { item , owner, startDate, endDate }
const bookItem = useMutation(CREATE_BOOKING_MUTATION, variables)
useEffect(() => {
if(!loading) {
bookItem(); // called when data ready
}
})
Another option: useApolloClient
:
useQuery
to load data needed in mutationconst client = useApolloClient();
useEffect
- conditionally (!loading
ordata
not empty) useclient.mutate()
with fetched (in query) data as variables;
Custom hook can be done with 3 parameters: (query, mutation, { mapDataToVariables })
Solution 2:
I think you can pass the variables when you actually call the mutation instead, something like:
...
const bookItem = useMutation(CREATE_BOOKING_MUTATION)
...
if(!loading && !error && data) {
bookItem({
variables: {
owner: data.posts[0].author.id,
...
}
})
}
Post a Comment for "How Do I Chain Usequery And Usemutation In Graphql Properly?"