├── .gitignore ├── .travis.yml ├── .babelrc ├── rollup.config.js ├── CONTRIBUTING.md ├── LICENSE ├── CHANGELOG.md ├── package.json ├── README.md └── src ├── index.js └── __tests__ └── index.js /.gitignore: -------------------------------------------------------------------------------- 1 | /coverage 2 | /demo/dist 3 | /dist 4 | /lib 5 | /es 6 | /node_modules 7 | /umd 8 | /es 9 | npm-debug.log 10 | .idea 11 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | 3 | node_js: 4 | - "7" 5 | 6 | cache: 7 | directories: 8 | - node_modules 9 | 10 | before_install: 11 | - npm install codecov 12 | 13 | after_success: 14 | - cat ./coverage/lcov.info | ./node_modules/codecov/bin/codecov 15 | 16 | cache: 17 | directories: 18 | - node_modules 19 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "env", 5 | { 6 | "modules": false, 7 | "loose": true 8 | } 9 | ], 10 | "stage-0", 11 | "react" 12 | ], 13 | "env": { 14 | "test": { 15 | "presets": [ 16 | [ 17 | "env", 18 | { 19 | "loose": true 20 | } 21 | ], 22 | "stage-0", 23 | "react" 24 | ] 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import babel from 'rollup-plugin-babel'; 2 | import fs from 'fs' 3 | 4 | const pkg = JSON.parse(fs.readFileSync('./package.json')) 5 | 6 | export default { 7 | entry: 'src/index.js', 8 | external: ['react'], 9 | exports: 'named', 10 | globals: { react: 'React' }, 11 | useStrict: false, 12 | sourceMap: true, 13 | plugins: [babel({ 14 | exclude: 'node_modules/**' 15 | })], 16 | targets: [ 17 | {dest: pkg.main, format: 'cjs'}, 18 | {dest: pkg.module, format: 'es'}, 19 | {dest: pkg['umd:main'], format: 'umd', moduleName: pkg.name} 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Prerequisites 2 | 3 | [Node.js](http://nodejs.org/) >= v4 must be installed. 4 | 5 | ## Installation 6 | 7 | - Running `npm install` in the module's root directory will install everything you need for development. 8 | 9 | ## Running Tests 10 | 11 | - `npm test` will run the tests once. 12 | 13 | - `npm run test:coverage` will run the tests and produce a coverage report in `coverage/`. 14 | 15 | - `npm run test:watch` will run the tests on every change. 16 | 17 | ## Building 18 | 19 | - `npm run build` will build the module for publishing to npm. 20 | 21 | - `npm run clean` will delete built resources. 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Kye Hohenberger 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Changelog 2 | ------------ 3 | 4 | ##### 2.0.0 5 | * Action creators now receive ONE arguement, `store`. 6 | This expands what is possible in an action handler 7 | 8 | * Renamed `addReducer` to `handleActions` (inspired by redux-actions) 9 | The name no longer made sense. Returning a _new_ state from the handler is no longer required. 10 | 11 | * Added `createActions` (inspired by redux-actions) 12 | 13 | Allows developer to create actions and have them available directly from the store 14 | ```js 15 | store.createActions({ 16 | startMediaStream: (constraints) => async store => { 17 | try { 18 | const stream = await navigator.mediaDevices.getUserMedia(constraints) 19 | store.actions.mediaStreamSuccess(stream) 20 | } catch (err) { 21 | store.actions.mediaStreamError(err) 22 | } 23 | }, 24 | addImage: 'camera/ADD_IMAGE' 25 | }) 26 | 27 | // ...later 28 | store.actions.startMediaStream({ audio: true, video: true }) 29 | store.actions.addImage(image) 30 | ``` 31 | 32 | If the property of the action creator is a plain string like `addImage: 'camera/ADD_IMAGE'` you can use the name in your reducer. 33 | 34 | ```js 35 | store.handleActions({ 36 | [store.actions.addImage]: (state, image) => { 37 | state.camera.images.push(image) 38 | } 39 | }) 40 | ``` 41 | 42 | * Reserved event types with the prefix `$$store:` 43 | `$$store:state:change` is fired after an action handler is called 44 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "holen", 3 | "version": "2.0.0", 4 | "description": "Declarative fetch in React", 5 | "jsnext:main": "dist/holen.es.js", 6 | "module": "dist/holen.es.js", 7 | "main": "dist/holen.js", 8 | "umd:main": "dist/holen.umd.js", 9 | "files": [ 10 | "dist" 11 | ], 12 | "scripts": { 13 | "build": "npm-run-all clean -p rollup -p minify:* -s size", 14 | "clean": "rimraf dist", 15 | "test": "standard src test && jest --coverage", 16 | "test:watch": "jest --watch", 17 | "rollup": "rollup -c", 18 | "minify:cjs": "uglifyjs $npm_package_main -cm toplevel -o $npm_package_main -p relative --in-source-map ${npm_package_main}.map --source-map ${npm_package_main}.map", 19 | "minify:umd": "uglifyjs $npm_package_umd_main -cm -o $npm_package_umd_main -p relative --in-source-map ${npm_package_umd_main}.map --source-map ${npm_package_umd_main}.map", 20 | "size": "echo \"Gzipped Size: $(strip-json-comments --no-whitespace $npm_package_main | gzip-size)\"", 21 | "release": "npm run test && npm run build && npm version patch && npm publish && git push --tags" 22 | }, 23 | "peerDependencies": { 24 | "react": ">=14" 25 | }, 26 | "devDependencies": { 27 | "babel-eslint": "^7.2.3", 28 | "babel-jest": "^19.0.0", 29 | "babel-polyfill": "^6.23.0", 30 | "babel-preset-env": "^1.4.0", 31 | "babel-preset-react": "^6.24.1", 32 | "babel-preset-stage-0": "^6.24.1", 33 | "gzip-size-cli": "^2.0.0", 34 | "hapi": "^16.1.0", 35 | "isomorphic-unfetch": "^2.0.0", 36 | "jest": "^19.0.2", 37 | "npm-run-all": "^4.0.2", 38 | "pretty-bytes-cli": "^2.0.0", 39 | "prop-types": "^15.5.8", 40 | "raw-loader": "^0.5.1", 41 | "react": "^15.5.4", 42 | "react-addons-test-utils": "^15.5.1", 43 | "react-dom": "^15.5.4", 44 | "rimraf": "^2.6.1", 45 | "rollup": "^0.41.6", 46 | "rollup-plugin-babel": "^2.7.1", 47 | "standard": "^10.0.2", 48 | "strip-json-comments-cli": "^1.0.1", 49 | "uglify-js": "^2.8.22" 50 | }, 51 | "author": "Kye Hohenberger", 52 | "homepage": "https://github.com/tkh44/holen#readme", 53 | "license": "MIT", 54 | "repository": { 55 | "type": "git", 56 | "url": "git+https://github.com/tkh44/holen.git" 57 | }, 58 | "directories": { 59 | "test": "tests" 60 | }, 61 | "keywords": [ 62 | "fetch", 63 | "react", 64 | "react-component", 65 | "react-fetch", 66 | "fetch-component", 67 | "preact", 68 | "preact-fetch", 69 | "holen" 70 | ], 71 | "eslintConfig": { 72 | "extends": "standard", 73 | "parser": "babel-eslint" 74 | }, 75 | "standard": { 76 | "parser": "babel-eslint", 77 | "ignore": [ 78 | "/dist/" 79 | ] 80 | }, 81 | "bugs": { 82 | "url": "https://github.com/tkh44/holen/issues" 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Holen 4 | Declarative fetch in React 5 | 6 | [![npm version](https://badge.fury.io/js/holen.svg)](https://badge.fury.io/js/holen) 7 | [![Build Status](https://travis-ci.org/tkh44/holen.svg?branch=master)](https://travis-ci.org/tkh44/holen) 8 | [![codecov](https://codecov.io/gh/tkh44/holen/branch/master/graph/badge.svg)](https://codecov.io/gh/tkh44/holen) 9 | 10 | - [Install](#install) 11 | - [Basic Usage](#basic-usage) 12 | 13 | ## Install 14 | 15 | ```bash 16 | npm install -S holen 17 | ``` 18 | 19 | ## Basic Usage 20 | ```jsx 21 | // Fetch on mount 22 | 23 | {({data}) =>
{JSON.stringify(data, null, 2)}
} 24 |
25 | 26 | // Lazy fetch 27 | 28 | {({fetching, data, fetch, error}) => ( 29 |
30 | 31 |
{JSON.stringify(data, null, 2)}
32 |
33 | )} 34 |
35 | ``` 36 | 37 | ## Props 38 | 39 | **body** `any` 40 | 41 | ```jsx 42 | 47 | {({data}) =>
{JSON.stringify(data, null, 2)}
} 48 |
49 | ``` 50 | 51 | *[MDN - Body](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Body)* 52 | 53 | **children** `function` 54 | 55 | Children is a function that receives an object as its only argument. 56 | 57 | The object contains the following keys: 58 | 59 | - fetching: `bool` 60 | - response: `object` 61 | - data: `object` 62 | - error: `object` 63 | - fetch: `function` 64 | 65 | ```jsx 66 | 67 | {({data}) =>
{data.name}
} 68 |
69 | ``` 70 | 71 | **credentials** `string` 72 | 73 | *[MDN - Credentials](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Sending_a_request_with_credentials_included)* 74 | 75 | **headers** `string` 76 | 77 | *[MDN - Headers](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Headers)* 78 | 79 | **lazy** `boolean` 80 | 81 | If true then the component will **not** perform the fetch on mount. 82 | You must use the `fetch` named argument in order to initiate the request. 83 | 84 | ```jsx 85 | 86 | {({fetching}) => {fetching &&
Loading
}} // renders nothing, fetch was not started 87 |
88 | ``` 89 | 90 | **method** `string` - *default `GET`* 91 | 92 | *[MDN - Method](https://developer.mozilla.org/en-US/docs/Web/API/Request/method)* 93 | 94 | **onResponse** `function` 95 | 96 | callback called on the response. 97 | 98 | ```jsx 99 | const handleResponse = (error, response) => { 100 | if (error || !response.ok) { 101 | panic() 102 | } 103 | 104 | cheer() 105 | } 106 | 107 | 111 | {({ data, fetch }) => ( 112 |
113 | 114 |
{JSON.stringify(data, null , 2)}
115 |
116 | )} 117 |
118 | ``` 119 | 120 | **transformResponse** `function` - *default `data => data`* 121 | 122 | The `transformResponse` prop is a function that can be used to massage the response data. It receives one argument, `data`, and by default, performs an identity operation, returning the data passed to it. 123 | 124 | **type** `string` - *default `json`* 125 | 126 | The [body method](https://developer.mozilla.org/en-US/docs/Web/API/Body) applied to 127 | the response. One of `json`, `text`, `blob`, `arrayBuffer` or `formData`. 128 | 129 | **url** `string` 130 | 131 | url of the request. 132 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import PropTypes from 'prop-types' 3 | 4 | function childrenToArray (children) { 5 | return Array.isArray && Array.isArray(children) 6 | ? children 7 | : [].concat(children) 8 | } 9 | 10 | export default class Holen extends React.Component { 11 | state = { 12 | fetching: !this.props.lazy, 13 | response: undefined, 14 | data: undefined, 15 | error: undefined 16 | } 17 | 18 | componentDidMount () { 19 | if (this.props.lazy) { 20 | return 21 | } 22 | this.doFetch() 23 | } 24 | 25 | componentWillReceiveProps (nextProps) { 26 | // only refresh when keys with primitive types change 27 | const refreshProps = ['url', 'method', 'lazy', 'type', 'body'] 28 | if (refreshProps.some(key => this.props[key] !== nextProps[key])) { 29 | this.doFetch(nextProps) 30 | } 31 | } 32 | 33 | componentWillUnmount () { 34 | this.willUnmount = true 35 | } 36 | 37 | doFetch = options => { 38 | const { url, body, credentials, headers, method } = Object.assign( 39 | {}, 40 | this.props, 41 | options 42 | ) 43 | 44 | this.setState({ fetching: true }) 45 | 46 | const updateState = (error, response) => { 47 | if (this.willUnmount) { 48 | return 49 | } 50 | 51 | this.setState( 52 | { 53 | data: 54 | response && response.data 55 | ? this.props.transformResponse(response.data) 56 | : undefined, 57 | error, 58 | fetching: false, 59 | response 60 | }, 61 | () => { 62 | this.props.onResponse(error, response) 63 | } 64 | ) 65 | } 66 | 67 | // eslint-disable-next-line no-undef 68 | return fetch(url, { 69 | body, 70 | credentials, 71 | headers, 72 | method 73 | }) 74 | .then(res => { 75 | if (this.willUnmount) { 76 | return 77 | } 78 | 79 | const bodyMethod = res[this.props.type] 80 | return bodyMethod.apply(res).then(data => { 81 | res.data = data 82 | return res 83 | }) 84 | }) 85 | .then(res => { 86 | updateState(undefined, res) 87 | return res 88 | }) 89 | .catch(e => { 90 | updateState(e, undefined) 91 | return e 92 | }) 93 | } 94 | 95 | render () { 96 | if (!this.props.children) { 97 | return null 98 | } 99 | 100 | const renderFn = 101 | this.props.render || childrenToArray(this.props.children)[0] 102 | return ( 103 | renderFn({ 104 | fetching: this.state.fetching, 105 | response: this.state.response, 106 | data: this.state.data, 107 | error: this.state.error, 108 | fetch: this.doFetch 109 | }) || null 110 | ) 111 | } 112 | } 113 | 114 | Holen.propTypes = { 115 | body: PropTypes.any, 116 | children: PropTypes.func, 117 | credentials: PropTypes.oneOf(['omit', 'same-origin', 'include']), 118 | headers: PropTypes.object, 119 | lazy: PropTypes.bool, 120 | method: PropTypes.oneOf([ 121 | 'get', 122 | 'post', 123 | 'put', 124 | 'patch', 125 | 'delete', 126 | 'options', 127 | 'head', 128 | 'GET', 129 | 'POST', 130 | 'PUT', 131 | 'PATCH', 132 | 'DELETE', 133 | 'OPTIONS', 134 | 'HEAD' 135 | ]), 136 | onResponse: PropTypes.func, 137 | url: PropTypes.string.isRequired, 138 | type: PropTypes.oneOf([ 139 | 'json', 140 | 'text', 141 | 'blob', 142 | 'arrayBuffer', 143 | 'formData' 144 | ]), 145 | transformResponse: PropTypes.func 146 | } 147 | 148 | Holen.defaultProps = { 149 | method: 'get', 150 | type: 'json', 151 | onResponse: () => {}, 152 | transformResponse: data => data 153 | } 154 | -------------------------------------------------------------------------------- /src/__tests__/index.js: -------------------------------------------------------------------------------- 1 | /* eslint-env jest */ 2 | import 'isomorphic-unfetch' 3 | import Holen from '../index' 4 | const Hapi = require('hapi') 5 | const React = require('react') 6 | const TestUtils = require('react-dom/test-utils') 7 | 8 | describe('holen', () => { 9 | test('can render with no children', () => { 10 | TestUtils.renderIntoDocument() 11 | }) 12 | 13 | test('makes request on mount', done => { 14 | const server = new Hapi.Server() 15 | server.connection() 16 | 17 | server.route({ 18 | method: 'GET', 19 | path: '/', 20 | handler: (request, reply) => { 21 | return reply({message: 'hello'}) 22 | } 23 | }) 24 | 25 | server.start(err => { 26 | expect(err).toBeUndefined() 27 | let runCount = 0 28 | 29 | const renderCb = ({data, fetching, fetch, error}) => { 30 | expect(error).toBeUndefined() 31 | expect(fetch).toBeInstanceOf(Function) 32 | expect(fetching).toBe(runCount < 2) 33 | 34 | if (data) { 35 | expect(data.message).toBe('hello1') 36 | } 37 | ++runCount 38 | return
39 | } 40 | 41 | TestUtils.renderIntoDocument( 42 | { 45 | expect(err).toBeUndefined() 46 | expect(res.data.message).toBe('hello1') 47 | expect(res.ok).toBe(true) 48 | server.stop(done) 49 | }} 50 | transformResponse={(data) => { 51 | data.message += '1' 52 | return data 53 | }} 54 | url={'http://localhost:' + server.connections[0].info.port} 55 | > 56 | {renderCb} 57 | 58 | ) 59 | }) 60 | }) 61 | 62 | test('makes lazy request', done => { 63 | const server = new Hapi.Server() 64 | server.connection() 65 | 66 | server.route({ 67 | method: 'POST', 68 | path: '/', 69 | handler: (request, reply) => { 70 | expect(request.headers).toHaveProperty( 71 | 'test-header', 72 | 'yes this is a test' 73 | ) 74 | return reply(request.payload) 75 | } 76 | }) 77 | 78 | server.start(err => { 79 | expect(err).toBeUndefined() 80 | let runCount = 0 81 | 82 | const renderCb = ({data, fetching, fetch, error}) => { 83 | expect(error).toBeUndefined() 84 | expect(fetching).toBe(runCount === 1) 85 | 86 | if (data) { 87 | expect(data.message).toBe('hello') 88 | } 89 | if (runCount === 0) { 90 | setTimeout(() => { 91 | fetch() 92 | }) 93 | } 94 | 95 | ++runCount 96 | return
97 | } 98 | 99 | TestUtils.renderIntoDocument( 100 | { 108 | expect(err).toBeUndefined() 109 | expect(res.data.message).toBe('hello') 110 | expect(res.ok).toBe(true) 111 | server.stop(done) 112 | }} 113 | url={'http://localhost:' + server.connections[0].info.port} 114 | > 115 | {renderCb} 116 | 117 | ) 118 | }) 119 | }) 120 | 121 | test('handles request error', done => { 122 | const server = new Hapi.Server() 123 | server.connection() 124 | 125 | server.route({ 126 | method: 'GET', 127 | path: '/', 128 | handler: (request, reply) => { 129 | return reply('something') 130 | } 131 | }) 132 | 133 | server.start(err => { 134 | expect(err).toBeUndefined() 135 | let runCount = 0 136 | 137 | const renderCb = ({data, fetching, fetch, error}) => { 138 | if (runCount === 2) { 139 | expect(error).toBeDefined() 140 | } 141 | 142 | ++runCount 143 | return
144 | } 145 | 146 | TestUtils.renderIntoDocument( 147 | { 149 | expect(err).toBeDefined() 150 | server.stop(done) 151 | }} 152 | url={'http://localaaaaaahost'} 153 | > 154 | {renderCb} 155 | 156 | ) 157 | }) 158 | }) 159 | 160 | test('handles json parse error', done => { 161 | const server = new Hapi.Server() 162 | server.connection() 163 | 164 | server.route({ 165 | method: 'GET', 166 | path: '/', 167 | handler: (request, reply) => { 168 | return reply('something') 169 | } 170 | }) 171 | 172 | server.start(err => { 173 | expect(err).toBeUndefined() 174 | let runCount = 0 175 | 176 | const renderCb = ({data, fetching, fetch, error}) => { 177 | if (runCount === 2) { 178 | expect(error).toBeDefined() 179 | } 180 | 181 | ++runCount 182 | return
183 | } 184 | 185 | TestUtils.renderIntoDocument( 186 | { 188 | server.stop(done) 189 | }} 190 | url={'http://localhost:' + server.connections[0].info.port} 191 | > 192 | {renderCb} 193 | 194 | ) 195 | }) 196 | }) 197 | }) 198 | --------------------------------------------------------------------------------