Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!