Here is an example of custom hook around Apollo mutation, which includes error and loading states to keep UX in sync with what is happening.
BTW you can check React Hook around Apollo GraphQL query
here.
import * as RH from "@apollo/react-hooks";
import gql from "graphql-tag";
// activate user query
export const ACTIVATE_USER_MUTATION = gql`
mutation ActivateUserMutation($input: ActivateUserInput) {
activateUser(input: $input) {
firstName
lastName
online
id
}
}
`;
// entity mutation hook
export const useActivateUserMutation = () => {
// gql hook
const [activateUser, { data, loading, error }] = RH.useMutation(ACTIVATE_USER_MUTATION);
const handleActivateUser = async (variables) => {
try {
const {
data: {
activateUser: { id }
}
} = await activateUser({ variables });
// call fn to show some success box in the interface
return id;
} catch (error) {
// parse error here
console.log(error.graphQLErrors)
}
};
return {
activateUser: handleActivateUser, // mutation handler
result: data, // mutation result
isLoading: loading, // loading state
error // mutation error state
};
};
More tips and best practices on my twitter.
Feedback is appreciated. Cheers!
Top comments (6)
Hi Max!
Thanks for sharing your experience! May you please describe what are benefits using you approach versus
graphql
HOC?This approach allows you to:
1) keep things reusable
2) keep things in one place
Nice!
Just getting into Apollo and React so this might be a silly question. But this very much like a functional component that has a Apollo hook in it with relevant return values. How is this a custom hook compared to a functional component?
Looks great!
You can generate these hooks automatically using GraphQL-Codegen:
How to configure GraphQL-Codegen and React Apollo Client to do work for you
Jack Gardner ・ ・ 5 min read
Medium