Skip to content

Instantly share code, notes, and snippets.

@albertdugba
Created April 30, 2021 21:52
Show Gist options
  • Save albertdugba/1638c149422384d5ec3c4aa0702e629f to your computer and use it in GitHub Desktop.
Save albertdugba/1638c149422384d5ec3c4aa0702e629f to your computer and use it in GitHub Desktop.
import { useMutation, useQueryClient } from 'react-query';
const queryClient = useQueryClient();
const handleFileChange = event => {
setBookName(event.target.files[0].name);
setSelectedBook(event.target.files[0]);
};
const handleFileUpload = event => {
event.preventDefault();
let formData = new FormData();
formData.append('file', selectedBook);
formData.append('file', bookName);
handleFileUploadMutation.mutate(formData);
};
const showPhotosFromUnsplash = () =>
setShowImagePicker(prevState => !prevState);
//======================= Book upload Mutation Function
const handleFileUploadMutation = useMutation(
payload => () =>
axios
.post('https://httpbin.org/post', payload, {
onUploadProgress: progressEvent => {
const percentageCompleted =
Math.round(progressEvent.loaded * 100) / progressEvent.total;
setCompleted(percentageCompleted);
setTimeout(() => setCompleted(0), 5000);
},
})
.then(res => console.log(res.data)),
{
onMutate: async payload => {
const [file, filename] = payload.getAll('file');
const url = URL.createObjectURL(file);
const oldBooks = queryClient.cancelQueries('books');
queryClient.setQueryData('books', old => [
...(old ?? []),
{
title: payload.title,
author: payload.author,
description: payload.description,
selectedImg: selectedImg,
},
]);
return oldBooks;
},
onError: (err, variables, recover) =>
typeof recover === 'function' ? recover() : null,
onSuccess: data => queryClient.setQueryData('books', data),
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment