From a5113b9247e78fc2659588e7ff6ae7cbd28d507c Mon Sep 17 00:00:00 2001 From: Vu Tien Khang Date: Mon, 5 Jul 2021 12:39:30 +0200 Subject: [PATCH] docs: examples/browser-create-react-app (#3694) Co-authored-by: kvutien Co-authored-by: Marcin Rataj --- README.md | 75 +++++++++--------------- screenshot.png => images/screenshot.png | Bin src/App.js | 51 ++++++++-------- src/hooks/use-ipfs-factory.js | 71 +++++++++++----------- src/hooks/use-ipfs.js | 30 ++++++---- test.js | 2 +- 6 files changed, 111 insertions(+), 118 deletions(-) rename screenshot.png => images/screenshot.png (100%) diff --git a/README.md b/README.md index 1d07fd7fc3..32effb8912 100755 --- a/README.md +++ b/README.md @@ -2,28 +2,41 @@ 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.
Open [http://localhost:3000](http://localhost:3000) to view it in the browser. @@ -31,57 +44,25 @@ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.
You will also see any lint errors in the console. -### `npm test` +#### `npm test` Launches the test runner in the interactive watch mode.
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.
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.
-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 diff --git a/screenshot.png b/images/screenshot.png similarity index 100% rename from screenshot.png rename to images/screenshot.png diff --git a/src/App.js b/src/App.js index f742be5208..a3e9bc9adf 100755 --- a/src/App.js +++ b/src/App.js @@ -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 (
@@ -26,27 +29,29 @@ const App = () => { ) } -const Title = ({ children }) => { - return ( -

{children}

- ) -} - const IpfsId = (props) => { - if (!props) return null - return ( -
-

Connected to IPFS

-
- {['id', 'agentVersion'].map((key) => ( -
- {key} -
{props[key]}
-
- ))} -
-
- ) + // 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 ( +
+

Connected – properties of current IPFS node

+
+ {['id', 'agentVersion'].map((key) => ( +
+ {key} +
{props[key]}
+
+ ))} +
+
+ ) } -export default App +const Title = ({ children }) => { + return ( +

{children}

+ ) + } + + export default App diff --git a/src/hooks/use-ipfs-factory.js b/src/hooks/use-ipfs-factory.js index dcd4da6607..b369a40f4e 100644 --- a/src/hooks/use-ipfs-factory.js +++ b/src/hooks/use-ipfs-factory.js @@ -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 @@ -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 } } diff --git a/src/hooks/use-ipfs.js b/src/hooks/use-ipfs.js index 39678bb16b..5e48089100 100644 --- a/src/hooks/use-ipfs.js +++ b/src/hooks/use-ipfs.js @@ -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) } diff --git a/test.js b/test.js index 812769aca0..6c3c11dcd7 100644 --- a/test.js +++ b/test.js @@ -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()