useMutation for file uploading (mutation progress) #1098
-
It's possible to make multi part request using useMutation and somehow get upload progress? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 12 replies
-
18 Thumbs Up and no answer ? |
Beta Was this translation helpful? Give feedback.
-
axios supports it, have you tried that? https://gist.github.com/virolea/e1af9359fe071f24de3da3500ff0f429 Generally, this is likely out of scope for react-query, because it is agnostic towards the actual querying / mutating. |
Beta Was this translation helpful? Give feedback.
-
Old question but I want to share my way of solving the problem. Because mutation function variables are agnostic enough (default type is any). I pass a callback function to track I do post to express with uses multer. This example can handle single file per request. const post_path = '/api/upload';
export interface UseMutationUploadFileVariables {
ParentLink_Category: string,
ParentLink_RecID: string,
RecId: string
progressCallBack?: (progressEvent: ProgressEvent) => void
file: File
}
const mutationFn_UploadFile = async (variables: UseMutationUploadFileVariables) => {
const { ParentLink_Category, ParentLink_RecID, file, progressCallBack, RecId } = variables
let fd = new FormData();
//* order of appends matter, add file as last one, api endpoint is express with multer.
fd.append("ParentLink_Category", ParentLink_Category)
fd.append("ParentLink_RecID", ParentLink_RecID)
fd.append("RecId", RecId)
fd.append("uploaded_file", file)
const axiosResponse = await axios.post<any, AxiosResponse<any>, FormData>(post_path, fd,
{
headers: {
"Content-Type": "multipart/form-data",
"Accept": "*/*"
},
onUploadProgress: (progressEvent: ProgressEvent) => {
progressCallBack && progressCallBack(progressEvent)
}
});
return axiosResponse
} |
Beta Was this translation helpful? Give feedback.
-
If you are using graphql-request for posting GraphQL requests, then you do not need any extra code to upload file. You can upload with react-query const UPDATE_IMAGE = gql`
mutation updateImage($projectId: String!, $logoImage: Upload, $previewImage: Upload) {
updateImage(projectId: $projectId, logoImage: $logoImage, previewImage: $previewImage) {
previewImageUrl
logoImageUrl
}
}
`;
const {mutate} = useMutation(async (params: any) => await request(GRAPHQL_BASE_URL, UPDATE_IMAGE, {...params}))
mutate({
projectId: '1',
projectImage: data.basics.projectImage, // JavaScript File
logoImage: data.basics.logoImage // JavaScript File
})
You can refer to graphql-request docs to see more example |
Beta Was this translation helpful? Give feedback.
Old question but I want to share my way of solving the problem.
Because mutation function variables are agnostic enough (default type is any). I pass a callback function to track
ProgressEvent
inonUploadProgress
I do post to express with uses multer. This example can handle single file per request.