Skip to content

Instantly share code, notes, and snippets.

@blindibrasil
Created November 1, 2019 17:20
Show Gist options
  • Save blindibrasil/dc5d0e903bd4af3b298efb35358aec17 to your computer and use it in GitHub Desktop.
Save blindibrasil/dc5d0e903bd4af3b298efb35358aec17 to your computer and use it in GitHub Desktop.
Upload - RocketSeat - Hook
import React, { useState, useEffect, useCallback } from 'react';
import { uniqueId } from 'lodash';
import Dropzone from 'react-dropzone';
import filesize from 'filesize';
import { CircularProgressbar } from 'react-circular-progressbar';
import { MdCheckCircle, MdError, MdLink } from 'react-icons/md';
import api from '~/services/api';
import {
Container,
Content,
FileInfo,
Preview,
DropContainer,
UploadMessage,
} from './styles';
export default function Pending({ documentId }) {
const [uploadedFiles, setUploadedFiles] = useState([]);
const updateFile = useCallback(
(id, data) => {
const files = uploadedFiles.map(uploadedFile => {
return id === uploadedFile.id
? { ...uploadedFile, ...data }
: uploadedFile;
});
setUploadedFiles(files);
},
[uploadedFiles]
);
useEffect(() => {
async function getDoc() {
const response = await api.get(`documents/${documentId}/files`);
// console.log(response.data)
const files = response.data.map(file => ({
id: file.id,
name: file.name,
readableSize: filesize(file.size),
uploaded: true,
url: file.url,
}));
setUploadedFiles(files);
}
getDoc();
}, [documentId]);
function processUpload(file) {
const data = new FormData();
data.append('document', file.file, file.name);
api
.post(`documents/${documentId}/files`, data, {
onUploadProgress: e => {
const calc = Math.round((e.loaded * 100) / e.total);
const progress = parseInt(calc, 10);
updateFile(file.id, {
progress,
});
},
})
.then(response => {
updateFile(file.id, {
uploaded: true,
id: response.data.id,
url: response.data.url,
});
})
.catch(() => {
updateFile(file.id, {
error: true,
});
});
}
function handleUpload(files) {
const uploadedFile = files.map(file => ({
file,
id: uniqueId(),
name: file.name,
readableSize: filesize(file.size),
progress: 0,
uploaded: false,
error: false,
url: null,
}));
setUploadedFiles(uploadedFiles.concat(uploadedFile));
uploadedFile.forEach(file => processUpload(file));
}
async function handleDelete(id) {
await api.delete(`documents/${documentId}/files/${id}`);
setUploadedFiles(uploadedFiles.filter(file => file.id !== id));
}
function renderDragMessage(isDragActive, isDragReject) {
if (!isDragActive) {
return <UploadMessage>Arraste arquivos aqui...</UploadMessage>;
}
if (isDragReject) {
return <UploadMessage type="error">Arquivo não suportado</UploadMessage>;
}
return <UploadMessage type="success">Solte os arquivos aqui</UploadMessage>;
}
return (
<Container>
<Content>
<Dropzone
accept="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
onDropAccepted={file => handleUpload(file)}
>
{({ getRootProps, getInputProps, isDragActive, isDragReject }) => (
<DropContainer
{...getRootProps()}
isDragActive={isDragActive}
isDragReject={isDragReject}
>
<input {...getInputProps()} />
{renderDragMessage(isDragActive, isDragReject)}
</DropContainer>
)}
</Dropzone>
{uploadedFiles &&
uploadedFiles.map(files => (
<li key={files.id}>
<FileInfo>
<Preview src="https://lh3.googleusercontent.com/9kABykeGovHPy-dN19lRxxnCp8IZK3Pkl8qLFNxrEe-hhKVZeiyhTBEIRUt6t-vhxQ" />
<div>
<strong>{files.name}</strong>
<span>
{files.readableSize}
{!!files.url && (
<button
type="button"
onClick={() => handleDelete(files.id)}
>
Excluir
</button>
)}
</span>
</div>
</FileInfo>
<div>
{!files.uploaded && !files.error && (
<CircularProgressbar
styles={{
root: { width: 24 },
path: { stroke: '#7159c1' },
}}
strokeWidth={10}
value={files.progress}
/>
)}
{files.url && (
<a href={files.url} target="_blank" rel="noopener noreferrer">
<MdLink style={{ marginRight: 8 }} size={24} color="#222" />
</a>
)}
{files.uploaded && <MdCheckCircle size={24} color="#78e5d5" />}
{files.error && <MdError size={24} color="#e57878" />}
</div>
</li>
))}
</Content>
</Container>
);
}
@blindibrasil
Copy link
Author

blindibrasil commented Nov 1, 2019

Preciso de ajuda, estou precisando implementar o upload de arquivos baseado no vídeo [Upload de arquivos: front-end com ReactJS | Diego Fernandes : https://youtu.be/G5UZmvkLWSQ ] só que está acontecendo o seguinte erro:
1 - Toda vez que envio o arquivo para fazer o upload após o carregamento completo do arquivo ele some, e se eu atualizar a página ai ele aparece corretamente.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment