├── .env.example
├── public
├── favicon.ico
├── robots.txt
├── manifest.json
└── index.html
├── src
├── graphql
│ ├── listNotesQuery.js
│ ├── removeNoteMutation.js
│ ├── createNoteMutation.js
│ └── updateNoteMutation.js
├── setupTests.js
├── NotesHApp.test.js
├── index.css
├── mock-dnas
│ ├── mockCallZome.js
│ └── mockData.js
├── schema.js
├── index.js
├── apolloClient.js
├── NotesHApp.css
├── resolvers.js
├── holochainClient.js
├── NotesHApp.js
└── serviceWorker.js
├── .gitignore
├── package.json
└── README.md
/.env.example:
--------------------------------------------------------------------------------
1 | REACT_APP_DNA_INTERFACE_URL=ws://localhost:3400
2 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/holochain/happ-ui-template/HEAD/public/favicon.ico
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/src/graphql/listNotesQuery.js:
--------------------------------------------------------------------------------
1 | import gql from "graphql-tag"
2 |
3 | export default gql`
4 | query ListNotes {
5 | listNotes {
6 | id
7 | createdAt
8 | title
9 | content
10 | }
11 | }
12 | `
13 |
--------------------------------------------------------------------------------
/src/graphql/removeNoteMutation.js:
--------------------------------------------------------------------------------
1 | import gql from 'graphql-tag'
2 |
3 | export default gql`
4 | mutation RemoveNote($id: String) {
5 | removeNote (id: $id) {
6 | id
7 | createdAt
8 | title
9 | content
10 | }
11 | }
12 | `
13 |
--------------------------------------------------------------------------------
/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom/extend-expect';
6 |
--------------------------------------------------------------------------------
/src/graphql/createNoteMutation.js:
--------------------------------------------------------------------------------
1 | import gql from 'graphql-tag'
2 |
3 | export default gql`
4 | mutation CreateNote($noteInput: NoteInput) {
5 | createNote (noteInput: $noteInput) {
6 | id
7 | createdAt
8 | title
9 | content
10 | }
11 | }
12 | `
13 |
--------------------------------------------------------------------------------
/src/graphql/updateNoteMutation.js:
--------------------------------------------------------------------------------
1 | import gql from 'graphql-tag'
2 |
3 | export default gql`
4 | mutation UpdateNote($id: String, $noteInput: NoteInput) {
5 | updateNote (id: $id, noteInput: $noteInput) {
6 | id
7 | createdAt
8 | title
9 | content
10 | }
11 | }
12 | `
13 |
--------------------------------------------------------------------------------
/src/NotesHApp.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { render } from '@testing-library/react'
3 | import NotesHApp from './NotesHApp'
4 |
5 | test('renders learn react link', () => {
6 | const { getByText } = render( )
7 | const divElement = getByText(/Notes hApp/i)
8 | expect(divElement).toBeInTheDocument()
9 | })
10 |
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "hApp",
3 | "name": "Create hApp Template",
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 | }
16 |
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/src/mock-dnas/mockCallZome.js:
--------------------------------------------------------------------------------
1 | import mockData from './mockData'
2 | import { isFunction } from 'lodash/fp'
3 |
4 | export default function mockCallZome (instanceId, zome, zomeFunc) {
5 | return async function (args) {
6 | const funcOrResult = mockData[instanceId][zome][zomeFunc]
7 | const result = isFunction(funcOrResult) ? funcOrResult(args) : funcOrResult
8 | return JSON.stringify({ Ok: result })
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/schema.js:
--------------------------------------------------------------------------------
1 | import gql from 'graphql-tag'
2 |
3 | export default gql`
4 |
5 | type Note {
6 | id: ID
7 | createdAt: String
8 | title: String
9 | content: String
10 | }
11 |
12 | input NoteInput {
13 | title: String
14 | content: String
15 | }
16 |
17 | type Query {
18 | getNote(id: String): Note
19 | listNotes: [Note]
20 | }
21 |
22 | type Mutation {
23 | createNote(noteInput: NoteInput): Note
24 | updateNote(id: String, noteInput: NoteInput): Note
25 | removeNote(id: String): Note
26 | }
27 | `
28 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
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 | .directory
16 | .DS_Store
17 | .env.local
18 | .env.development.local
19 | .env.test.local
20 | .env.production.local
21 | .env
22 |
23 | .holochain
24 | dna-src/dna
25 | conductor-config.toml
26 | agent-1.key
27 |
28 | npm-debug.log*
29 | yarn-debug.log*
30 | yarn-error.log*
31 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import ReactDOM from 'react-dom'
3 | import { ApolloProvider } from '@apollo/react-hooks'
4 | import apolloClient from './apolloClient'
5 | import './index.css'
6 | import NotesHApp from './NotesHApp'
7 | import * as serviceWorker from './serviceWorker'
8 |
9 | function HApp () {
10 | return
11 |
12 |
13 | }
14 |
15 | ReactDOM.render( , document.getElementById('root'))
16 |
17 | // If you want your app to work offline and load faster, you can change
18 | // unregister() to register() below. Note this comes with some pitfalls.
19 | // Learn more about service workers: https://bit.ly/CRA-PWA
20 | serviceWorker.unregister()
21 |
--------------------------------------------------------------------------------
/src/apolloClient.js:
--------------------------------------------------------------------------------
1 | import { ApolloClient } from 'apollo-client'
2 | import { SchemaLink } from 'apollo-link-schema'
3 | import { makeExecutableSchema } from 'graphql-tools'
4 | import apolloLogger from 'apollo-link-logger'
5 | import { ApolloLink } from 'apollo-link'
6 | import { InMemoryCache } from 'apollo-cache-inmemory'
7 |
8 | import typeDefs from './schema'
9 | import resolvers from './resolvers'
10 |
11 | const schemaLink = new SchemaLink({ schema: makeExecutableSchema({ typeDefs, resolvers }) })
12 |
13 | const link = ApolloLink.from([
14 | apolloLogger,
15 | schemaLink
16 | ])
17 |
18 | const apolloClient = new ApolloClient({
19 | link,
20 | cache: new InMemoryCache(),
21 | connectToDevTools: true
22 | })
23 |
24 | export default apolloClient
25 |
--------------------------------------------------------------------------------
/src/NotesHApp.css:
--------------------------------------------------------------------------------
1 | .notes-happ {
2 | display: flex;
3 | padding: 50px;
4 | align-items: center;
5 | flex-direction: column;
6 | }
7 |
8 | .note-card {
9 | border: 1px solid lightgray;
10 | border-radius: 4px;
11 | padding: 0px 20px 20px;
12 | margin-bottom: 20px;
13 | width: 400px;
14 | }
15 |
16 | .note-content {
17 | margin-bottom: 20px;
18 | }
19 |
20 | .note-form {
21 | border: 1px solid lightgray;
22 | border-radius: 4px;
23 | padding: 0px 20px 20px;
24 | margin-bottom: 20px;
25 | width: 400px;
26 | }
27 |
28 | .form-row {
29 | display: flex;
30 | margin-bottom: 20px;
31 | }
32 |
33 | .form-row > label {
34 | flex: 1
35 | }
36 |
37 | .form-row > input {
38 | flex: 4;
39 | }
40 |
41 | .form-row > textarea {
42 | flex: 4;
43 | }
44 |
45 | button {
46 | margin-right: 10px;
47 | }
--------------------------------------------------------------------------------
/src/resolvers.js:
--------------------------------------------------------------------------------
1 | import { createZomeCall } from './holochainClient'
2 |
3 | function dnaToUiNote (noteResult) {
4 | return {
5 | ...noteResult,
6 | createdAt: noteResult.created_at
7 | }
8 | }
9 |
10 | export const resolvers = {
11 | Query: {
12 | getNote: async (_, { id }) =>
13 | dnaToUiNote(await createZomeCall('/react-graphql/notes/get_note')({ id })),
14 |
15 | listNotes: async () =>
16 | (await createZomeCall('/react-graphql/notes/list_notes')()).map(dnaToUiNote)
17 | },
18 |
19 | Mutation: {
20 | createNote: async (_, { noteInput }) =>
21 | dnaToUiNote(await createZomeCall('/react-graphql/notes/create_note')({ note_input: noteInput })),
22 |
23 | updateNote: async (_, { id, noteInput }) =>
24 | dnaToUiNote(await createZomeCall('/react-graphql/notes/update_note')({ id, note_input: noteInput })),
25 |
26 | removeNote: async (_, { id }) =>
27 | dnaToUiNote(await createZomeCall('/react-graphql/notes/remove_note')({ id }))
28 | }
29 | }
30 |
31 | export default resolvers
32 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "happ-ui-template",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@apollo/react-hooks": "^3.1.3",
7 | "@holochain/hc-web-client": "^0.5.3",
8 | "@testing-library/jest-dom": "^4.2.4",
9 | "@testing-library/react": "^9.3.2",
10 | "@testing-library/user-event": "^7.1.2",
11 | "apollo-cache-inmemory": "^1.6.5",
12 | "apollo-client": "^2.6.8",
13 | "apollo-link": "^1.2.13",
14 | "apollo-link-logger": "^1.2.3",
15 | "apollo-link-schema": "^1.2.4",
16 | "graphql": "^14.6.0",
17 | "graphql-tag": "^2.10.3",
18 | "graphql-tools": "^4.0.6",
19 | "lodash": "^4.17.15",
20 | "react": "^16.12.0",
21 | "react-dom": "^16.12.0",
22 | "react-scripts": "3.3.1"
23 | },
24 | "scripts": {
25 | "start": "npm run start:mock",
26 | "start:mock": "REACT_APP_MOCK_DNA_CONNECTION='true' react-scripts start",
27 | "start:live": "REACT_APP_MOCK_DNA_CONNECTION='false' react-scripts start",
28 | "build": "react-scripts build",
29 | "test": "react-scripts test",
30 | "eject": "react-scripts eject",
31 | "hc:start": "holochain -c ./conductor-config.toml"
32 | },
33 | "eslintConfig": {
34 | "extends": "react-app"
35 | },
36 | "browserslist": {
37 | "production": [
38 | ">0.2%",
39 | "not dead",
40 | "not op_mini all"
41 | ],
42 | "development": [
43 | "last 1 chrome version",
44 | "last 1 firefox version",
45 | "last 1 safari version"
46 | ]
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | hApp
28 |
29 |
30 | You need to enable JavaScript to run this app.
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/src/mock-dnas/mockData.js:
--------------------------------------------------------------------------------
1 | // data is a tree organized by instanceId > zome > function
2 | // leaves can either be an object, or a function which is called with the zome call args.
3 | // See mockCallZome.js
4 |
5 | const noteEntries = {
6 | QmRccTDUM1UcJWuxW3aMjfYkSBFmhBnGtgB7lAddress01: {
7 | created_at: '1581553349996',
8 | title: 'First note',
9 | content: 'This is the earliest note created'
10 | },
11 | QmRccTDUM1UcJWuxW3aMjfYkSBFmhBnGtgB7lAddress02: {
12 | created_at: '1581553400796',
13 | title: 'Middle note',
14 | content: 'Created after First note but before Latest note'
15 | },
16 | QmRccTDUM1UcJWuxW3aMjfYkSBFmhBnGtgB7lAddress03: {
17 | created_at: '1581553434263',
18 | title: 'Latest note',
19 | content: 'The most recently created note'
20 | }
21 | }
22 |
23 | const data = {
24 | notes: {
25 | notes: {
26 | create_note: ({ note_input: noteInput }) => {
27 | const noteIndex = Object.keys(noteEntries).length + 1
28 | const id = 'QmRccTDUM1UcJWuxW3aMjfYkSBFmhBnGtgB7lAddress0' + noteIndex
29 | const createdAt = String(Date.now())
30 | noteEntries[id] = { id, ...noteInput, created_at: createdAt }
31 | return {
32 | id,
33 | created_at: createdAt,
34 | ...noteInput
35 | }
36 | },
37 |
38 | get_note: ({ id }) => {
39 | const noteEntry = noteEntries[id]
40 | if (!noteEntry) throw new Error(`Can't find note with id ${id}`)
41 | return {
42 | id,
43 | ...noteEntry
44 | }
45 | },
46 |
47 | update_note: ({ id, note_input: noteInput }) => {
48 | const noteOriginalResult = data.notes.notes.get_note({ id })
49 | noteEntries[id] = { ...noteOriginalResult, ...noteInput }
50 | return {
51 | ...noteOriginalResult,
52 | ...noteInput
53 | }
54 | },
55 |
56 | remove_note: ({ id }) => {
57 | const removedNote = data.notes.notes.get_note({ id })
58 | delete noteEntries[id]
59 | return removedNote
60 | },
61 |
62 | list_notes: () => Object.keys(noteEntries)
63 | .map(key => ({
64 | id: key,
65 | ...noteEntries[key]
66 | }))
67 | .sort((a, b) => a.created_at > b.created_at ? -1 : 1)
68 | }
69 | }
70 | }
71 |
72 | export default data
73 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
2 |
3 | ## Available Scripts
4 |
5 | In the project directory, you can run:
6 |
7 | ### `yarn start`
8 |
9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
11 |
12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console.
14 |
15 | ### `yarn test`
16 |
17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
19 |
20 | ### `yarn build`
21 |
22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance.
24 |
25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed!
27 |
28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
29 |
30 | ### `yarn eject`
31 |
32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
33 |
34 | 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.
35 |
36 | 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.
37 |
38 | 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.
39 |
40 | ## Learn More
41 |
42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
43 |
44 | To learn React, check out the [React documentation](https://reactjs.org/).
45 |
46 | ### Code Splitting
47 |
48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
49 |
50 | ### Analyzing the Bundle Size
51 |
52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
53 |
54 | ### Making a Progressive Web App
55 |
56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
57 |
58 | ### Advanced Configuration
59 |
60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
61 |
62 | ### Deployment
63 |
64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
65 |
66 | ### `yarn build` fails to minify
67 |
68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
69 |
--------------------------------------------------------------------------------
/src/holochainClient.js:
--------------------------------------------------------------------------------
1 | import { connect as hcWebClientConnect } from '@holochain/hc-web-client'
2 | import { get } from 'lodash/fp'
3 | import mockCallZome from './mock-dnas/mockCallZome'
4 |
5 | let holochainClient
6 |
7 | // NB: This should be set to false when you want to run against a Holochain Conductor
8 | // with a websocket interface running on REACT_APP_DNA_INTERFACE_URL.
9 | export const MOCK_DNA_CONNECTION = process.env.REACT_APP_MOCK_DNA_CONNECTION === 'true' || false
10 |
11 | export const HOLOCHAIN_LOGGING = process.env.NODE_ENV === 'development'
12 |
13 | async function initAndGetHolochainClient () {
14 | if (holochainClient) return holochainClient
15 |
16 | try {
17 | holochainClient = await hcWebClientConnect({
18 | url: process.env.REACT_APP_DNA_INTERFACE_URL,
19 | wsClient: { max_reconnects: 0 }
20 | })
21 |
22 | if (HOLOCHAIN_LOGGING) {
23 | console.log('🎉 Successfully connected to Holochain!')
24 | }
25 | return holochainClient
26 | } catch (error) {
27 | if (HOLOCHAIN_LOGGING) {
28 | console.log('😞 Holochain client connection failed -- ', error.toString())
29 | }
30 | throw (error)
31 | }
32 | }
33 |
34 | export function parseZomeCallPath (zomeCallPath) {
35 | const [zomeFunc, zome, instanceId] = zomeCallPath.split('/').reverse()
36 |
37 | return { instanceId, zome, zomeFunc }
38 | }
39 |
40 | export function createZomeCall (zomeCallPath, callOpts = {}) {
41 | const DEFAULT_OPTS = {
42 | logging: HOLOCHAIN_LOGGING
43 | }
44 | const opts = {
45 | ...DEFAULT_OPTS,
46 | ...callOpts
47 | }
48 |
49 | return async function (args = {}) {
50 | try {
51 | const { instanceId, zome, zomeFunc } = parseZomeCallPath(zomeCallPath)
52 | let zomeCall
53 | if (MOCK_DNA_CONNECTION) {
54 | zomeCall = mockCallZome(instanceId, zome, zomeFunc)
55 | } else {
56 | await initAndGetHolochainClient()
57 | zomeCall = holochainClient.callZome(instanceId, zome, zomeFunc)
58 | }
59 |
60 | const rawResult = await zomeCall(args)
61 | const jsonResult = JSON.parse(rawResult)
62 | const error = get('Err', jsonResult) || get('SerializationError', jsonResult)
63 | const rawOk = get('Ok', jsonResult)
64 |
65 | if (error) throw (error)
66 |
67 | const result = rawOk
68 |
69 | if (opts.logging) {
70 | const detailsFormat = 'font-weight: bold; color: rgb(220, 208, 120)'
71 |
72 | console.groupCollapsed(
73 | `👍 ${zomeCallPath}%c zome call complete`,
74 | 'font-weight: normal; color: rgb(160, 160, 160)'
75 | )
76 | console.groupCollapsed('%cArgs', detailsFormat)
77 | console.log(args)
78 | console.groupEnd()
79 | console.groupCollapsed('%cResult', detailsFormat)
80 | console.log(result)
81 | console.groupEnd()
82 | console.groupEnd()
83 | }
84 | return result
85 | } catch (error) {
86 | console.log(
87 | `👎 %c${zomeCallPath}%c zome call ERROR using args: `,
88 | 'font-weight: bold; color: rgb(220, 208, 120); color: red',
89 | 'font-weight: normal; color: rgb(160, 160, 160)',
90 | args,
91 | ' -- ',
92 | error
93 | )
94 | }
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/src/NotesHApp.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react'
2 | import { pick } from 'lodash/fp'
3 | import { useQuery, useMutation } from '@apollo/react-hooks'
4 | import LIST_NOTES_QUERY from './graphql/listNotesQuery'
5 | import CREATE_NOTE_MUTATION from './graphql/createNoteMutation'
6 | import UPDATE_NOTE_MUTATION from './graphql/updateNoteMutation'
7 | import REMOVE_NOTE_MUTATION from './graphql/removeNoteMutation'
8 |
9 | import './NotesHApp.css'
10 |
11 | function NotesHApp () {
12 | const { data: { listNotes } = { listNotes: [] } } = useQuery(LIST_NOTES_QUERY)
13 |
14 | const [createNote] = useMutation(CREATE_NOTE_MUTATION, { refetchQueries: [{ query: LIST_NOTES_QUERY }] })
15 | const [updateNote] = useMutation(UPDATE_NOTE_MUTATION)
16 | const [removeNote] = useMutation(REMOVE_NOTE_MUTATION, { refetchQueries: [{ query: LIST_NOTES_QUERY }] })
17 |
18 | // the id of the note currently being edited
19 | const [editingNoteId, setEditingNoteId] = useState()
20 |
21 | return
22 |
Notes hApp
23 |
24 |
createNote({ variables: { noteInput } })}
26 | formTitle='Create Note' />
27 |
28 |
29 | {listNotes.map(note =>
30 | )}
37 |
38 |
39 | }
40 |
41 | function NoteRow ({ note, editingNoteId, setEditingNoteId, updateNote, removeNote }) {
42 | const { id } = note
43 |
44 | if (id === editingNoteId) {
45 | return updateNote({ variables: { id, noteInput } })} />
50 | }
51 |
52 | return
53 | }
54 |
55 | function NoteCard ({ note: { id, title, content }, setEditingNoteId, removeNote }) {
56 | return
57 |
{title}
58 |
{content}
59 |
setEditingNoteId(id)}>Edit
60 |
removeNote({ variables: { id } })}>Remove
61 |
62 | }
63 |
64 | function NoteForm ({ note = { title: '', content: '' }, formTitle, formAction, setEditingNoteId = () => {} }) {
65 | const [formState, setFormState] = useState(pick(['title', 'content'], note))
66 | const { title, content } = formState
67 | const { id } = note
68 |
69 | const setField = field => ({ target: { value } }) => setFormState(formState => ({
70 | ...formState,
71 | [field]: value
72 | }))
73 |
74 | const clearForm = () => {
75 | setFormState({
76 | title: '',
77 | content: ''
78 | })
79 | }
80 |
81 | const onSubmit = () => {
82 | formAction({
83 | id,
84 | noteInput: {
85 | ...formState
86 | }
87 | })
88 | setEditingNoteId(null)
89 | clearForm()
90 | }
91 |
92 | const onCancel = () => {
93 | setEditingNoteId(null)
94 | clearForm()
95 | }
96 |
97 | return
98 |
{formTitle}
99 |
100 | Title
101 |
102 |
103 |
104 | Content
105 |
106 |
107 |
108 | Submit
109 | Cancel
110 |
111 |
112 | }
113 |
114 | export default NotesHApp
115 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl, {
104 | headers: { 'Service-Worker': 'script' }
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready.then(registration => {
134 | registration.unregister();
135 | });
136 | }
137 | }
138 |
--------------------------------------------------------------------------------