Skip to content
This repository was archived by the owner on Feb 12, 2024. It is now read-only.

Commit 37631d9

Browse files
olizillaAlan Shaw
authored and
Alan Shaw
committed
docs: add example for js-ipfs with create-react-app v2 (#1871)
License: MIT Signed-off-by: Oli Evans <oli@tableflip.io>
1 parent 7cba3dd commit 37631d9

File tree

15 files changed

+349
-0
lines changed

15 files changed

+349
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# required because react-scripts scans *up* the tree from this project and finds
2+
# a conflicting version of eslint in the node_modules dir for js-ipfs.
3+
SKIP_PREFLIGHT_CHECK=true
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
/.pnp
6+
.pnp.js
7+
8+
# testing
9+
/coverage
10+
11+
# production
12+
/build
13+
14+
# misc
15+
.DS_Store
16+
.env.local
17+
.env.development.local
18+
.env.test.local
19+
.env.production.local
20+
21+
npm-debug.log*
22+
yarn-debug.log*
23+
yarn-error.log*
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
## IPFS React app
2+
3+
A minimal demonstration of how to use js-ipfs in a `create-react-app` generated app.
4+
5+
It boots up a js-ipfs instance via a custom React hook in `./src/hooks/use-ipfs-factory.js`, which is called from `./src/App.js`, which is where the magic happens.
6+
7+
![Screen shot of the js ipfs node id info](./screenshot.png)
8+
9+
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). **v2.1.3**
10+
11+
## Available Scripts
12+
13+
In the project directory, you can run:
14+
15+
### `npm start`
16+
17+
Runs the app in the development mode.<br>
18+
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
19+
20+
The page will reload if you make edits.<br>
21+
You will also see any lint errors in the console.
22+
23+
### `npm test`
24+
25+
Launches the test runner in the interactive watch mode.<br>
26+
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
27+
28+
### `npm run build`
29+
30+
Builds the app for production to the `build` folder.<br>
31+
It correctly bundles React in production mode and optimizes the build for the best performance.
32+
33+
The build is minified and the filenames include the hashes.<br>
34+
Your app is ready to be deployed!
35+
36+
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
37+
38+
### `npm run eject`
39+
40+
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
41+
42+
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
43+
44+
Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
45+
46+
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
47+
48+
## Learn More
49+
50+
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
51+
52+
To learn React, check out the [React documentation](https://reactjs.org/).
53+
54+
### Code Splitting
55+
56+
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
57+
58+
### Analyzing the Bundle Size
59+
60+
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
61+
62+
### Making a Progressive Web App
63+
64+
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
65+
66+
### Advanced Configuration
67+
68+
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
69+
70+
### Deployment
71+
72+
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
73+
74+
### `npm run build` fails to minify
75+
76+
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
{
2+
"name": "ipfs-react-demo",
3+
"version": "0.1.0",
4+
"private": true,
5+
"dependencies": {
6+
"dot-prop": "^4.2.0",
7+
"ipfs": "file:../../",
8+
"ipfs-css": "^0.12.0",
9+
"react": "^16.8.0",
10+
"react-dom": "^16.8.0",
11+
"react-scripts": "2.1.3",
12+
"tachyons": "^4.11.1"
13+
},
14+
"scripts": {
15+
"start": "react-scripts start",
16+
"build": "react-scripts build",
17+
"test": "react-scripts test",
18+
"eject": "react-scripts eject"
19+
},
20+
"eslintConfig": {
21+
"extends": "react-app"
22+
},
23+
"browserslist": [
24+
">0.2%",
25+
"not dead",
26+
"not ie <= 11",
27+
"not op_mini all"
28+
]
29+
}
Binary file not shown.
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8" />
5+
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
6+
<meta
7+
name="viewport"
8+
content="width=device-width, initial-scale=1, shrink-to-fit=no"
9+
/>
10+
<meta name="theme-color" content="#000000" />
11+
<!--
12+
manifest.json provides metadata used when your web app is added to the
13+
homescreen on Android. See https://developers.google.com/web/fundamentals/web-app-manifest/
14+
-->
15+
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
16+
<!--
17+
Notice the use of %PUBLIC_URL% in the tags above.
18+
It will be replaced with the URL of the `public` folder during the build.
19+
Only files inside the `public` folder can be referenced from the HTML.
20+
21+
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
22+
work correctly both with client-side routing and a non-root public URL.
23+
Learn how to configure a non-root public URL by running `npm run build`.
24+
-->
25+
<title>IPFS React App</title>
26+
</head>
27+
<body>
28+
<noscript>You need to enable JavaScript to run this app.</noscript>
29+
<div id="root"></div>
30+
<!--
31+
This HTML file is a template.
32+
If you open it directly in the browser, you will see an empty page.
33+
34+
You can add webfonts, meta tags, or analytics to this file.
35+
The build step will place the bundled scripts into the <body> tag.
36+
37+
To begin the development, run `npm start` or `yarn start`.
38+
To create a production bundle, use `npm run build` or `yarn build`.
39+
-->
40+
</body>
41+
</html>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"short_name": "React App",
3+
"name": "Create React App Sample",
4+
"icons": [
5+
{
6+
"src": "favicon.ico",
7+
"sizes": "64x64 32x32 24x24 16x16",
8+
"type": "image/x-icon"
9+
}
10+
],
11+
"start_url": ".",
12+
"display": "standalone",
13+
"theme_color": "#000000",
14+
"background_color": "#ffffff"
15+
}
Loading
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import React from 'react'
2+
import useIpfsFactory from './hooks/use-ipfs-factory.js'
3+
import useIpfs from './hooks/use-ipfs.js'
4+
import logo from './ipfs-logo.svg'
5+
6+
const App = () => {
7+
const { ipfs, ipfsInitError } = useIpfsFactory({commands: ['id']})
8+
const id = useIpfs(ipfs, 'id')
9+
return (
10+
<div className='sans-serif'>
11+
<header className="flex items-center pa3 bg-navy bb bw3 b--aqua">
12+
<a href="https://ipfs.io" title="home">
13+
<img alt="IPFS logo" src={logo} style={{ height: 50 }} className='v-top' />
14+
</a>
15+
<h1 className="flex-auto ma0 tr f3 fw2 montserrat aqua">IPFS React</h1>
16+
</header>
17+
<main>
18+
{ipfsInitError && (
19+
<div className='bg-yellow pa4 mw7 center mv4 white'>
20+
Error: {ipfsInitError.message || ipfsInitError}
21+
</div>
22+
)}
23+
{id && <IpfsId {...id} />}
24+
</main>
25+
</div>
26+
)
27+
}
28+
29+
const Title = ({children}) => {
30+
return (
31+
<h2 className="f5 ma0 pb2 tracked aqua fw4 montserrat">{children}</h2>
32+
)
33+
}
34+
35+
const IpfsId = (props) => {
36+
if (!props) return null
37+
return (
38+
<section className='bg-snow mw7 center mt5'>
39+
<h1 className='f3 fw4 ma0 pv3 aqua montserrat tc'>Connected to IPFS</h1>
40+
<div className='pa4'>
41+
{['id', 'agentVersion'].map((key) => (
42+
<div className="mb4" key={key}>
43+
<Title>{key}</Title>
44+
<div className='bg-white pa2 br2 truncate monospace'>{props[key]}</div>
45+
</div>
46+
))}
47+
</div>
48+
</section>
49+
)
50+
}
51+
52+
export default App
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import React from 'react'
2+
import ReactDOM from 'react-dom'
3+
import App from './App'
4+
5+
it('renders without crashing', () => {
6+
const div = document.createElement('div')
7+
ReactDOM.render(<App />, div)
8+
ReactDOM.unmountComponentAtNode(div)
9+
});
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import Ipfs from 'ipfs'
2+
import { useEffect, useState } from 'react'
3+
4+
let ipfs = null
5+
6+
/*
7+
* A quick demo using React hooks to create an ipfs instance.
8+
*
9+
* Hooks are brand new at the time of writing, and this pattern
10+
* is intended to show it is possible. I don't know if it is wise.
11+
*
12+
* Next steps would be to store the ipfs instance on the context
13+
* so use-ipfs calls can grab it from there rather than expecting
14+
* it to be passed in.
15+
*/
16+
export default function useIpfsFactory ({commands}) {
17+
const [isIpfsReady, setIpfsReady] = useState(!!ipfs)
18+
const [ipfsInitError, setIpfsInitError] = useState(null)
19+
20+
useEffect(() => {
21+
// The fn to useEffect should not return anything other than a cleanup fn,
22+
// So it cannot be marked async, which causes it to return a promise,
23+
// Hence we delegate to a async fn rather than making the param an async fn.
24+
startIpfs()
25+
return function cleanup () {
26+
if (ipfs && ipfs.stop) {
27+
console.log('Stopping IPFS')
28+
ipfs.stop()
29+
setIpfsReady(false)
30+
}
31+
}
32+
}, [])
33+
34+
async function startIpfs () {
35+
if (ipfs) {
36+
console.log('IPFS already started')
37+
38+
} else if (window.ipfs && window.ipfs.enable) {
39+
console.log('Found window.ipfs')
40+
ipfs = await window.ipfs.enable({commands})
41+
42+
} else {
43+
try {
44+
console.time('IPFS Started')
45+
ipfs = await promiseMeJsIpfs(Ipfs, {})
46+
console.timeEnd('IPFS Started')
47+
} catch (error) {
48+
console.error('IPFS init error:', error)
49+
ipfs = null
50+
setIpfsInitError(error)
51+
}
52+
}
53+
54+
setIpfsReady(!!ipfs)
55+
}
56+
57+
return {ipfs, isIpfsReady, ipfsInitError}
58+
}
59+
60+
function promiseMeJsIpfs (Ipfs, opts) {
61+
return new Promise((resolve, reject) => {
62+
const ipfs = new Ipfs(opts)
63+
ipfs.once('ready', () => resolve(ipfs))
64+
ipfs.once('error', err => reject(err))
65+
})
66+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import { useState, useEffect } from 'react'
2+
import dotProp from 'dot-prop'
3+
4+
/*
5+
* Pass the command you'd like to call on an ipfs instance.
6+
*
7+
* Uses setState to capture the response, so your component
8+
* will re-render when the result turns up.
9+
*
10+
*/
11+
export default function useIpfs (ipfs, cmd, opts) {
12+
const [res, setRes] = useState(null)
13+
useEffect(() => {
14+
callIpfs(ipfs, cmd, opts, setRes)
15+
}, [ipfs, cmd, opts])
16+
return res
17+
}
18+
19+
async function callIpfs (ipfs, cmd, opts, setRes) {
20+
if (!ipfs) return null
21+
console.log(`Call ipfs.${cmd}`)
22+
const ipfsCmd = dotProp.get(ipfs, cmd)
23+
const res = await ipfsCmd(opts)
24+
console.log(`Result ipfs.${cmd}`, res)
25+
setRes(res)
26+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
@import "../node_modules/tachyons";
2+
@import "../node_modules/ipfs-css";
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import React from 'react'
2+
import ReactDOM from 'react-dom'
3+
import './index.css'
4+
import App from './App'
5+
6+
ReactDOM.render(<App />, document.getElementById('root'))
Lines changed: 1 addition & 0 deletions
Loading

0 commit comments

Comments
 (0)