Skip to content

Instantly share code, notes, and snippets.

@acomito
Last active August 10, 2020 17:54
Show Gist options
  • Save acomito/d11f27106ba6f3f80881cfd4aad58b98 to your computer and use it in GitHub Desktop.
Save acomito/d11f27106ba6f3f80881cfd4aad58b98 to your computer and use it in GitHub Desktop.
import React, { useState } from 'react'
const FilesArea = ({ defaultFiles }) => {
const [localFiles, setLocalFiles] = useState([]);
const onUpload = (e) => {
let file = e.target.files[0];
let uploadedFilesLength = defaultFiles.length + localFiles.length; // figure out how many files the've uploaded thus far
if (uploadedFilesLength > 5) {
return setError('You can only upload 5 files!')
}
let res = await singleUpload({
variables: { file }
});
if (res.data.singleUpload.id) {
setLocalFiles([...localFiles, res.data.singleUpload]) // set the local files array to be the existing local files + the new upload/file at the end of the array
}
}
const onSave = () => {
await saveTask({
variables: {
taskId,
// for the files field, we want to first spread the existing files array (from backend) to the array THEN spread our new array of files after that
files: [
...defaultFiles.map(item => helpers.cleanTypename(item)), // e.g. [File, File]
...localFiles.map(item => helpers.cleanTypename(item)) // e.g. [File, File]
]
// above code with "... spread" will result in an array that looks like this [File, File, File, File] aka [existingFile, existingFile, newFile, newFile]
}
})
}
return (
<>
{localFiles && localFiles.length > 0 && localFiles.map(file => (
<div key={file.id}>
{file.filename}
</div>
))}
<UploadBtn onUpload={onUpload} />
</>
)
}
// assume that the task comes in from a component above, and so we can pass in our files to the FilesArea (or just to the modal) for use in the saveTask mutation
export default ({ task }) => {
return (
<>
<FilesArea defaultFiles={task.files} />
</>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment