'Advice: React Custom Hook with onClick and inline access to response

I've started using custom hook's in React, creating the following:

export function useLazyHook({ onCompleted, onError }) {
    // Apollo
    const client = useApolloClient()

    /**
     * Use State
     */

    const [loading, setLoading] = useState(false)
    const [data, setData] = useState(null)
    const [error, setError] = useState(null)

    /**
     * Method
     */

    const CallMe = async ({ input }) => {
        // Loading
        setLoading(true)
        try {
            const data = await client.mutate({
                mutation: MUTATION,
                variables: {
                    Input: input,
                },
            })
            setLoading(false)
            setData(data)
            return { error: null, data: data }
        } catch (error) {
            setError(error)
            if (error.graphQLErrors) {
                setError(error.graphQLErrors[0])
                return { error: error.graphQLErrors[0], data: null }
            }
        }
    }
    // Return
    return [{ loading, data, error }, CallMe]
}

The hook can be using in the following ways:

const [{ loading, data, error }, CallMe] = useLazyHook({
    onCompleted(res) {
        console.log(res)
    },
    onError(err) {
        console.log(err)
    },
})

We can access the loading, data and error var the declared variables or within the onCompleted and onError. We can also access the same data inline via:

const { error, data } = await CallMe({
    input: {},
})
console.log(error)
console.log(data)

All the above works fine, however, if there is something I'm missing or doing incorrectly then any advice is more than welcome.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source