Reputation: 4023
I'm currently using Apollo's React hooks for GraphQL authentication. I want to refactor a mutation so that I can use for all different logins like Google, Facebook, Twitter OAuth, etc.
import { useMutation } from '@apollo/react-hooks'
import { CREATE_POST_MUTATION } from '../../graphql/mutation'
const [createPost, { loading }] = useMutation(CREATE_POST_MUTATION, {
onCompleted: data => {
navigation.navigate("StatusModal", {
status: "postingSuccess",
screen: "Posting",
data,
})
},
onError: data => {
navigation.navigate("StatusModal", {
status: "postingError",
screen: "Posting",
})
},
})
const createPostHandler = async () => {
const { title, price, description, address } = value && value
try {
await createPost({
variables: {
title,
body: description,
price: Number(price),
location: location.toString(),
address,
}
})
} catch (err) {
throw new Error(err)
navigation.navigate("StatusModal", {
status: "postingError",
screen: "Posting",
})
}
}
export { createPostHandler as default }
Calling the above code shows the error that the React hooks can only be called inside the body of a functional component. How do I make this re-usable?
Upvotes: 1
Views: 101
Reputation: 8418
Hooks are running (can be executed) only in a "render flow" of a functional component, you can't run it in other context.
For reusing you can define a function containing useMutation
in external file/exported function and call/run it in many functional components.
Maybe you're looking for custom hooks?
Upvotes: 1