Skip to content

Commit

Permalink
docs: examples/browser-create-react-app (ipfs#3694)
Browse files Browse the repository at this point in the history
Co-authored-by: kvutien <kvutien@VTKT5.fritz.box>
Co-authored-by: Marcin Rataj <lidel@lidel.org>
  • Loading branch information
3 people committed Jul 5, 2021
1 parent 1ed1850 commit a5113b9
Show file tree
Hide file tree
Showing 6 changed files with 111 additions and 118 deletions.
75 changes: 28 additions & 47 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,86 +2,67 @@

A minimal demonstration of how to use js-ipfs in a `create-react-app` generated app.

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.
It boots up a js-ipfs instance (an IPFS node) via a custom React hook in `./src/hooks/use-ipfs-factory.js`, which is called from `./src/App.js`. Once the IPFS node is set up, `App.js` displays its ident and its version number.

![Screen shot of the js ipfs node id info](./screenshot.png)
> _Remember that a Peer ID of an IPFS node is [the multihash of the public key of this node](https://github.com/libp2p/specs/blob/master/peer-ids/peer-ids.md#peer-ids), and the public-private key pair of a node is generated by typing `ipfs init`._
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). **v2.1.3**
![Screen shot of the js ipfs node id info](./images/screenshot.png)

## Before you start

First clone this repo, install dependencies in the project root and build the project.
**Note**: this example is useful to learn how to spawn IPFS from a web page. It is also possible to [spawn an IPFS daemon from the command line](https://docs.ipfs.io/install/command-line/) with `ipfs daemon`. While self-hosting is advised, one can also delegate IPFS operations to a third-party like Infura. See tutorials [here](https://blog.infura.io/part-2-getting-started-with-ipfs-on-infura/) and [here](https://blog.infura.io/part-2-getting-started-with-ipfs-on-infura/).

## To start

First clone the whole repo, install dependencies limited to this project `browser-create-react-app` and run the demo.

```console
$ git clone https://github.com/ipfs/js-ipfs.git
$ cd js-ipfs
$ cd js-ipfs/examples/browser-create-react-app
$ npm install
$ npm run build
$ npm start
```
## Call structure in `App.js`
All React applications store their main logic in `App.js`:
* `App.js` renders the cosmetics of the demo and call `useIpfs` to retrieve the `id` of the node
* `useIpfsFactory.js` initialises and closes the IPFS local node
* `useIpfs.js` does the actual calls to IPFS to retrieve the property specified in argument (here the retrieved property is `id`, requested from `App.js`)

## Annexes
### Console message `[HMR] Waiting for update signal from WDS...`

## Available Scripts
This message comes from the hot reload capability of webpack, that can update the web app every time you save your development code. To remove it, see here: https://stackoverflow.com/questions/59695102/reactjs-console-error-hmr-waiting-for-update-signal-from-wds

### Available Scripts from create-react-app

In the project directory, you can run:

### `npm start`
#### `npm start`

Runs the app in the development mode.<br>
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.

The page will reload if you make edits.<br>
You will also see any lint errors in the console.

### `npm test`
#### `npm test`

Launches the test runner in the interactive watch mode.<br>
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `npm run build`
#### `npm run build`

Builds the app for production to the `build` folder.<br>
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.<br>
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
Your app is ready to be deployed! Read how to host a [single page](https://docs.ipfs.io/how-to/websites-on-ipfs/single-page-website/) or an [entire website](https://docs.ipfs.io/how-to/websites-on-ipfs/multipage-website/#prerequisites) on IPFS.

### `npm run eject`
But with modern hosting services like Heroku, Netlity or Fleek, you can skip the build because they will do a complete github deployment for you. See the React official page about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**

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.

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.

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.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).

### Code Splitting

This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting

### Analyzing the Bundle Size

This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size

### Making a Progressive Web App

This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app

### Advanced Configuration

This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration

### Deployment

This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
You can learn more on IPFS API in the [IPFS documentation](https://docs.ipfs.io/) and [IPFS npm documentation](https://www.npmjs.com/package/ipfs-http-client).

### `npm run build` fails to minify
Details how to use the File System abstraction of IPFS (add, cat, egt, ls etc.) are [here](https://github.com/ipfs/js-ipfs/blob/master/docs/core-api/FILES.md)

This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
File renamed without changes
51 changes: 28 additions & 23 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ import useIpfs from './hooks/use-ipfs.js'
import logo from './ipfs-logo.svg'

const App = () => {
const { ipfs, ipfsInitError } = useIpfsFactory({ commands: ['id'] })
const id = useIpfs(ipfs, 'id')
// there is no change when we comment out the args of useIpfsFactory -> remove args?
const { ipfs, ipfsInitError } = useIpfsFactory(/*{ commands: ['id'] }*/)
// retrieve id of the current peer (see https://github.com/ipfs/js-ipfs/blob/master/docs/core-api/MISCELLANEOUS.md)
const id = useIpfs(ipfs, 'id')

return (
<div className='sans-serif'>
<header className='flex items-center pa3 bg-navy bb bw3 b--aqua'>
Expand All @@ -26,27 +29,29 @@ const App = () => {
)
}

const Title = ({ children }) => {
return (
<h2 className='f5 ma0 pb2 tracked aqua fw4 montserrat'>{children}</h2>
)
}

const IpfsId = (props) => {
if (!props) return null
return (
<section className='bg-snow mw7 center mt5'>
<h1 className='f3 fw4 ma0 pv3 aqua montserrat tc' data-test='title'>Connected to IPFS</h1>
<div className='pa4'>
{['id', 'agentVersion'].map((key) => (
<div className='mb4' key={key}>
<Title>{key}</Title>
<div className='bg-white pa2 br2 truncate monospace' data-test={key}>{props[key]}</div>
</div>
))}
</div>
</section>
)
// the props of this component are all key-value pairs of the object 'id'
// prints out the values of the keys 'id' and 'agentVersion' of the object 'id'
if (!props) return null
return (
<section className='bg-snow mw7 center mt5'>
<h1 className='f3 fw4 ma0 pv3 aqua montserrat tc' data-test='title'>Connected – properties of current IPFS node</h1>
<div className='pa4'>
{['id', 'agentVersion'].map((key) => (
<div className='mb4' key={key}>
<Title>{key}</Title>
<div className='bg-white pa2 br2 truncate monospace' data-test={key}>{props[key]}</div>
</div>
))}
</div>
</section>
)
}

export default App
const Title = ({ children }) => {
return (
<h2 className='f5 ma0 pb2 tracked aqua fw4 montserrat'>{children}</h2>
)
}

export default App
71 changes: 37 additions & 34 deletions src/hooks/use-ipfs-factory.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import Ipfs from 'ipfs'
// ipfs is the core API, a CLI and a HTTP server that functions as a HTTP to IPFS bridge
// and an RPC endpoint. See https://www.npmjs.com/package/ipfs
import { useEffect, useState } from 'react'

let ipfs = null
Expand All @@ -14,44 +16,45 @@ let ipfs = null
* it to be passed in.
*/
export default function useIpfsFactory () {
const [isIpfsReady, setIpfsReady] = useState(Boolean(ipfs))
const [ipfsInitError, setIpfsInitError] = useState(null)
// initialise state variables, React hooks
const [isIpfsReady, setIpfsReady] = useState(Boolean(ipfs))
const [ipfsInitError, setIpfsInitError] = useState(null)

useEffect(() => {
// The fn to useEffect should not return anything other than a cleanup fn,
// So it cannot be marked async, which causes it to return a promise,
// Hence we delegate to a async fn rather than making the param an async fn.
async function startIpfs () {
if (ipfs) {
console.log('IPFS already started')
} else if (window.ipfs && window.ipfs.enable) {
console.log('Found window.ipfs')
ipfs = await window.ipfs.enable({ commands: ['id'] })
} else {
try {
console.time('IPFS Started')
ipfs = await Ipfs.create()
console.timeEnd('IPFS Started')
} catch (error) {
console.error('IPFS init error:', error)
ipfs = null
setIpfsInitError(error)
useEffect(() => {
// useEffect -as used here- is equivalent to componentDidMount in old React
// The hook useEffect should not return anything other than a cleanup fn,
// in addition, in a true life application there are many other context init things
// hence in this example we make only a call to an async that initialises IPFS
startIpfs()
// ... add here any other init fn as required by an application
return function cleanup () {
if (ipfs && ipfs.stop) {
console.log('Stopping IPFS')
ipfs.stop().catch(err => console.error(err))
ipfs = null
setIpfsReady(false)
}
}
}
}, [])

setIpfsReady(Boolean(ipfs))
}
async function startIpfs () {
// initialise IPFS daemon
if (ipfs) {
console.log('IPFS already started')
} else {
try {
console.time('IPFS Started') // start timer
ipfs = await Ipfs.create()
console.timeEnd('IPFS Started') // stop timer and log duration in console
} catch (error) {
console.error('IPFS init error:', error)
ipfs = null
setIpfsInitError(error)
}
}

startIpfs()
return function cleanup () {
if (ipfs && ipfs.stop) {
console.log('Stopping IPFS')
ipfs.stop().catch(err => console.error(err))
ipfs = null
setIpfsReady(false)
}
setIpfsReady(Boolean(ipfs))
}
}, [])

return { ipfs, isIpfsReady, ipfsInitError }
return { ipfs, isIpfsReady, ipfsInitError }
}
30 changes: 17 additions & 13 deletions src/hooks/use-ipfs.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,30 @@
import { useState, useEffect } from 'react'
import dotProp from 'dot-prop'
// dot-prop: used to obtain a property of an object when the name of property is a string
// here we get ipfs.id when calling dotProp.get(ipfs, cmd), with cmd = 'id'
// and we get ipfs.hash when calling with cmd = 'hash' etc.

/*
* Pass the command you'd like to call on an ipfs instance.
*
* Uses setState to capture the response, so your component
* will re-render when the result turns up.
* callIpfs uses setState write the response as a state variable, so that your component
* will re-render when the result 'res' turns up from the call await ipfsCmd.
*
*/
export default function useIpfs (ipfs, cmd, opts) {
const [res, setRes] = useState(null)
useEffect(() => {
callIpfs(ipfs, cmd, opts, setRes)
}, [ipfs, cmd, opts])
return res
// note: opts is not used here and is not passed as args of the call from App.js
const [res, setRes] = useState(null)
useEffect(() => {
callIpfs(ipfs, cmd, opts, setRes)
}, [ipfs, cmd, opts])
return res
}

async function callIpfs (ipfs, cmd, opts, setRes) {
if (!ipfs) return null
console.log(`Call ipfs.${cmd}`)
const ipfsCmd = dotProp.get(ipfs, cmd)
const res = await ipfsCmd(opts)
console.log(`Result ipfs.${cmd}`, res)
setRes(res)
if (!ipfs) return null
console.log(`Call ipfs.${cmd}`)
const ipfsCmd = dotProp.get(ipfs, cmd)
const res = await ipfsCmd(opts)
console.log(`Result ipfs.${cmd}`, res)
setRes(res)
}
2 changes: 1 addition & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module.exports = {
browser
.url(process.env.IPFS_EXAMPLE_TEST_URL)
.waitForElementVisible('[data-test=title]')
.assert.containsText('[data-test=title]', 'Connected to IPFS')
.assert.containsText('[data-test=title]', 'Connected – properties of current IPFS node')
.assert.elementPresent('[data-test=id')
.assert.elementPresent('[data-test=agentVersion')
.end()
Expand Down

0 comments on commit a5113b9

Please sign in to comment.