liquid-funding/app/components/projects/hooks.js

67 lines
2.2 KiB
JavaScript
Raw Normal View History

2019-03-07 16:42:25 +00:00
import EmbarkJS from 'Embark/EmbarkJS'
import web3 from 'Embark/web3'
2019-03-07 16:42:25 +00:00
import LiquidPledging from 'Embark/contracts/LiquidPledging'
import { useState, useEffect, useMemo } from 'react'
import { timeSinceBlock } from '../../utils/dates'
import { getFiles, ipfs } from '../../utils/ipfs'
import { databaseExists } from '../../utils/db'
async function getProjectAge(id, events, setState){
const event = events.find(e => e.returnValues.idProject === id)
const { timestamp } = await web3.eth.getBlock(event.blockNumber)
setState(timeSinceBlock(timestamp, 'days'))
}
2019-03-07 16:42:25 +00:00
async function getProjectAssets(projectId, setState){
EmbarkJS.onReady(async (err) => {
const projectInfo = await LiquidPledging.methods.getPledgeAdmin(projectId).call()
const CID = projectInfo.url.split('/').slice(-1)[0]
console.log({CID, projectInfo, ipfs})
2019-03-07 16:42:25 +00:00
getFiles(CID)
.then((files) => {
setState(files)
const manifest = files[2]
console.log({files}, JSON.parse(manifest.content))
})
.catch(async (err) => {
console.log('IPFS getFiles error: ', err)
databaseExists('ipfs')
.catch(() => location.reload())
getFiles(CID)
.then((files) => {
setState(files)
const manifest = files[2]
console.log({files}, JSON.parse(manifest.content))
})
.catch((err) => {
console.log('IPFS FAILED ON READY', err)
})
})
2019-03-07 16:42:25 +00:00
})
}
const getProjectManifest = assets => assets ? JSON.parse(assets.find(a => a.name.toLowerCase() === 'manifest.json').content) : null
export function useProjectData(projectId, profile, projectAddedEvents) {
const [projectAge, setAge] = useState(null)
const [projectAssets, setAssets] = useState(null)
const [ipfsReady, setIpfsState] = useState(null)
useEffect(() => {
ipfs.on('ready', () => { setIpfsState(true) })
}, [projectId])
useEffect(() => {
getProjectAge(projectId, projectAddedEvents, setAge)
}, [projectAddedEvents])
useEffect(() => {
2019-03-07 16:42:25 +00:00
getProjectAssets(projectId, setAssets)
}, [projectId, ipfsReady])
const manifest = useMemo(() => getProjectManifest(projectAssets), [projectAssets])
return { projectAge, projectAssets, manifest }
}