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

docs: examples/browser-create-react-app #3694

Merged
merged 8 commits into from
Jul 5, 2021
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 30 additions & 46 deletions examples/browser-create-react-app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,86 +2,70 @@

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 SHA-256 multihash of the public key of this node, and the public-private key pair of a node is generated by typing `ipfs init`._
lidel marked this conversation as resolved.
Show resolved Hide resolved

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
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). **v2.1.3**. It has been tested with `node` **v12.18.4** (`npm` **v6.14.6**) and `node` **v14.17.0** (`npm` **v7.13.0****)
lidel marked this conversation as resolved.
Show resolved Hide resolved

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 with `ipfs daemon`. For pragmatic uses, you may want to call directly the IPFS node run by Infura, see tutorial at https://blog.infura.io/part-2-getting-started-with-ipfs-on-infura/ and at https://github.com/kvutien/ipfs-dapp.
lidel marked this conversation as resolved.
Show resolved Hide resolved

## 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`. For this demo, the calling sequence of `App.js` is ![App.js](./images/appJsStructure.png)
* `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! For example drag-and-dropped in the Netlify manual installation page.
lidel marked this conversation as resolved.
Show resolved Hide resolved

### `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
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).

This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
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)

### `npm run build` fails to minify
To have a high level view of IPFS, check out the [ConsenSys blog](https://medium.com/@ConsenSys/an-introduction-to-ipfs-9bba4860abd0).
lidel marked this conversation as resolved.
Show resolved Hide resolved

This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
51 changes: 28 additions & 23 deletions examples/browser-create-react-app/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
77 changes: 42 additions & 35 deletions examples/browser-create-react-app/src/hooks/use-ipfs-factory.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
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

/*
* A quick demo using React hooks to create an ipfs instance.
* A quick demo using React hooks to create an ipfs instance. June 2020
lidel marked this conversation as resolved.
Show resolved Hide resolved
*
* Hooks are brand new at the time of writing, and this pattern
* is intended to show it is possible. I don't know if it is wise.
Expand All @@ -14,44 +16,49 @@ 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 if (window.ipfs && window.ipfs.enable) {
// legacy IPFS. Disabled. See here: https://docs.ipfs.io/how-to/companion-window-ipfs/
console.log('Found window.ipfs')
ipfs = await window.ipfs.enable({ commands: ['id'] })
lidel marked this conversation as resolved.
Show resolved Hide resolved
} 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 examples/browser-create-react-app/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)
}