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

228
Visualizações
Why am I getting invalid hooks error in the console?

I cannot figure out for the life of me why I'm getting this error when using mutations via React Query. Any sort of feedback would be appreciated.

Note: I'm using inside a function (React) component so I'm not sure why this error's getting thrown.

error:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

code:

const addAsset = (asset) => {
    return axios.post('http://localhost/api/file-upload', asset);
}

const fileUpload = () => {
    const url = 'http://localhost/api/file-upload';

    let formData = new FormData();
    let imagefile = document.querySelector('#file');
    formData.append("image", imagefile.files[0]);

    const headers = {
        "Accept": 'application/json',
        "Authorization": `Bearer ${authToken}`
    }

    axios.post(url, formData, {headers})
        .then(resp => {
            let okStatus       = resp.status;
            let successMessage = resp.data.message;

            if(okStatus) {
                setShow(false);
            }

            setUploadSuccess(okStatus);
            setStatusMessage(successMessage);
            setStatusCode(okStatus);
        }).catch(error => {
        let errorMessage       = error.response.data.message;
        let errorStatus        = error.response.status;

        setStatusMessage(errorMessage);
        setStatusCode(errorStatus);
    });

    const queryClient = useQueryClient();

    return useMutation(addAsset, {
        onSuccess: () => {
            queryClient.invalidateQueries('uploads');
        }
    });
}

return(<Button variant="primary" onClick={fileUpload}>Upload!</Button>);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As the error message says, hooks can only be called in the body of a function component. They cannot be called in an onClick callback. You will need to move the hook calls out of fileUpload.

const queryClient = useQueryClient();

const { mutate } = useMutation(addAsset, {
  onSuccess: () => {
    queryClient.invalidateQueries('uploads');
  }
});

const fileUpload = () => {
  const url = 'http://localhost/api/file-upload';
  // ...
  axios.post(url, formData, {headers})
     .then(
  // ...

  mutate(/* insert variables here */);
}

See also: Rules of Hooks

about 4 years ago · Juan Pablo Isaza Relatório
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