0

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.

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
HireLee
  • 561
  • 1
  • 9
  • 25
  • If the code is working as expected it sounds like you are asking for something more like a [codereview](https://codereview.stackexchange.com/https://codereview.stackexchange.com/). Is there something a bit more specific you'd like us to look at here with the code? – Drew Reese Feb 11 '22 at 08:23
  • @DrewReese thanks for your comment! It was more to provide the solution to others alongside stirring the pot to encourage discourse. A more specific question could be is the way Im calling (via onClick async event) and returning the data/loading/error semantically correct? – HireLee Feb 11 '22 at 08:48
  • I don't see any overt issues with your code. – Drew Reese Feb 11 '22 at 08:59

0 Answers0