Created
April 30, 2021 21:52
-
-
Save albertdugba/1638c149422384d5ec3c4aa0702e629f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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