ipfs/src/components/Add.tsx

76 lines
2.0 KiB
TypeScript
Raw Normal View History

2019-10-18 11:32:36 +02:00
import React, { useState, useEffect } from 'react'
import useIpfsApi, { IpfsConfig } from '../hooks/use-ipfs-api'
import { formatBytes, addToIpfs } from '../utils'
2019-10-18 11:32:36 +02:00
import { ipfsNodeUri, ipfsGateway } from '../../site.config'
2019-10-16 17:02:04 +02:00
import Dropzone from './Dropzone'
2019-10-17 00:13:54 +02:00
import styles from './Add.module.css'
2019-10-16 17:02:04 +02:00
import Spinner from './Spinner'
2019-10-18 11:32:36 +02:00
const { hostname, port, protocol } = new URL(ipfsNodeUri)
const ipfsConfig: IpfsConfig = {
protocol: protocol.replace(':', ''),
host: hostname,
port: port || '443'
}
2019-10-16 17:02:04 +02:00
export default function Add() {
2019-10-19 15:20:42 +02:00
const { ipfs, isIpfsReady, ipfsError } = useIpfsApi(ipfsConfig)
2019-10-17 00:13:54 +02:00
const [fileHash, setFileHash] = useState()
2019-10-16 17:02:04 +02:00
const [loading, setLoading] = useState(false)
2019-10-18 11:32:36 +02:00
const [message, setMessage] = useState()
const [error, setError] = useState()
const [fileSize, setFileSize] = useState()
const [fileSizeReceived, setFileSizeReceived] = useState('')
useEffect(() => {
setMessage(
`Adding to IPFS<br />
<small>${fileSizeReceived || 0}/${fileSize}</small><br />`
)
}, [fileSize, fileSizeReceived])
async function handleOnDrop(acceptedFiles: File[]) {
if (!acceptedFiles[0]) return
2019-10-16 17:02:04 +02:00
setLoading(true)
2019-10-18 11:32:36 +02:00
setError(null)
const totalSize = formatBytes(acceptedFiles[0].size, 0)
setFileSize(totalSize)
try {
2019-10-19 15:20:42 +02:00
const cid = await addToIpfs(acceptedFiles, setFileSizeReceived, ipfs)
2019-10-18 11:32:36 +02:00
if (!cid) return
setFileHash(cid)
setLoading(false)
} catch (error) {
setError(`Adding to IPFS failed: ${error.message}`)
return null
}
2019-10-16 17:02:04 +02:00
}
return (
2019-10-16 22:10:03 +02:00
<div className={styles.add}>
2019-10-16 17:02:04 +02:00
{loading ? (
2019-10-18 11:32:36 +02:00
<Spinner message={message} />
2019-10-16 17:02:04 +02:00
) : fileHash ? (
2019-10-16 17:26:46 +02:00
<a
target="_blank"
rel="noopener noreferrer"
href={`${ipfsGateway}/ipfs/${fileHash}`}
>
ipfs://{fileHash}
</a>
2019-10-16 17:02:04 +02:00
) : (
2019-10-19 15:20:42 +02:00
<Dropzone
multiple={false}
handleOnDrop={handleOnDrop}
disabled={!isIpfsReady}
error={error || ipfsError}
/>
2019-10-16 17:02:04 +02:00
)}
</div>
)
}