Skip to content

Instantly share code, notes, and snippets.

@philippetedajo
Created June 1, 2022 14:33
Show Gist options
  • Save philippetedajo/baf0813bf7ef83d1fca7b4c09ec04d0c to your computer and use it in GitHub Desktop.
Save philippetedajo/baf0813bf7ef83d1fca7b4c09ec04d0c to your computer and use it in GitHub Desktop.
const [progressInfos, setProgressInfos] = useState({ val: [] })
const progressRef = useRef(null)
const [uploadError, setUploadError] = useState(null)
const [uploadVideo] = useMutation(
gql`
mutation UploadVideo($input: UploadVideoInput!) {
uploadVideo(input: $input) {
id
}
}
`,
{
refetchQueries: ['VideosList'],
},
)
async function upload(id, file) {
const progression = [...progressRef.current.val]
await uploadVideo({
variables: {
input: {
name: file.name,
projectId,
file,
},
},
context: {
fetchOptions: {
onProgress: function onprogress(event) {
progression[id].percentage = Math.round(
(event.loaded / event.total) * 100,
)
setProgressInfos({ val: progression })
},
},
},
})
}
function onSelectFiles(e) {
e.preventDefault()
const files = Array.from([...e.target.files])
const progression = files.map(file => ({
percentage: 0,
fileName: file.name,
size: file.size,
}))
progressRef.current = { val: progression }
const uploadPromises = files.map((file, i) => upload(i, file))
Promise.all(uploadPromises)
.then(() => {
setProgressInfos({ val: [] })
})
.catch(err => {
setUploadError(err)
})
// reset the target value
e.target.value = ''
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment