Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda