'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>);
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nicholas Tower |
