I'm calling a custom hook within a React Component:
const [CallMe, { loading, data, error }] = useCustomHook({
onCompleted(res) {
console.log(res)
},
onError(err) {
console.log(err)
},
})
Which is initiated via an onClick event:
onClick={() => CallMe() }
The custom hook consists of the following:
export function useCustomHook({ onCompleted, onError }) {
/**
* Use State
*/
const [loading, setLoading] = useState(false)
const [data, setData] = useState(null)
const [error, setError] = useState(null)
/**
* Get Thing
*/
function GetThing() {
setLoading(true)
callExternalApi
.method()
.then(({ data, error }) => {
setLoading(false)
if (error) {
setError(error)
onError(error)
}
if (data) {
CALL TO MUTATION NEEDED HERE (NON HOOK)
}
})
}
return [GetThing, { loading: loading, data: data, error: error }]
}
When data has successfully been returned I want to fire a Mutation, however I don't want this to be done via the useMutation Apollo hook.
Therefore my question is how would I fire this mutation in a none hook manner that will still allow me to update the Apollo Cache on response all within this custom hook?
I understand that I can simply do a HTTP request via Fetch, but this wont give me the inMemoryCache advantage that Im using with throughout the app. Would I have to intializeApollo within the custom hook?
Any thoughts or suggestions are welcome.
It would appear that within my custom hook I can import Apollo Client, this then gives me the ability to use mutations and queries.
import { useApolloClient } from '@apollo/client'
Then within your exported custom hook:
client
.mutate({
mutation:MUTATION,
variables: {
Input: input,
},
})
.catch((error) => {
console.log(error)
})
.then((result) => {
console.log(result)})