├── .editorconfig ├── .eslintrc.js ├── .flowconfig ├── .gitignore ├── LICENSE ├── README.md ├── babel.config.js ├── index.js ├── package.json └── yarn.lock /.editorconfig: -------------------------------------------------------------------------------- 1 | 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | indent_size = 2 8 | indent_style = space 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | 15 | [*.{json,yml}] 16 | indent_size = 2 17 | indent_style = space 18 | 19 | [Makefile] 20 | indent_style = tab 21 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | // ESLint root is here 2 | 3 | process.chdir(__dirname); 4 | 5 | module.exports = { 6 | root: true, 7 | parser: 'babel-eslint', 8 | parserOptions: { 9 | allowImportExportEverywhere: true, 10 | codeFrame: false, 11 | }, 12 | extends: [ 13 | 'plugin:eslint-comments/recommended', 14 | 'plugin:promise/recommended', 15 | 'airbnb', 16 | ], 17 | plugins: [ 18 | 'promise', 19 | 'html', 20 | 'react-hooks', 21 | ], 22 | settings: { 23 | 'import/resolver': { 24 | webpack: { 25 | config: './webpack.config.js', 26 | }, 27 | }, 28 | }, 29 | rules: { 30 | 'import/prefer-default-export': 'off', // prefer named export 31 | 'space-before-function-paren': ['error', { 32 | anonymous: 'always', 33 | named: 'always', // use space 34 | asyncArrow: 'always', 35 | }], 36 | 'react/jsx-filename-extension': ['error', { 37 | extensions: ['.js'], // no .jsx 38 | }], 39 | 'eslint-comments/disable-enable-pair': ['error', { 40 | allowWholeFile: true, 41 | }], 42 | 'no-restricted-syntax': [ 43 | 'error', 44 | 'ForInStatement', 45 | 'LabeledStatement', 46 | 'WithStatement', 47 | "BinaryExpression[operator='in']", 48 | ], 49 | 'react-hooks/rules-of-hooks': 'error', 50 | 'spaced-comment': ['error', 'always', { markers: [':', '::'] }], 51 | 'react/require-default-props': 'off', // optional props without defaults 52 | 'react/sort-comp': 'off', // do not sort React class fields/methods 53 | 'object-curly-newline': ['warn', { 54 | ObjectExpression: { minProperties: 5, multiline: true, consistent: true }, 55 | ObjectPattern: { minProperties: 5, multiline: true, consistent: true }, 56 | ImportDeclaration: { minProperties: 5, multiline: true, consistent: true }, 57 | ExportDeclaration: { minProperties: 5, multiline: true, consistent: true }, 58 | }], 59 | 'quote-props': ['warn', 'as-needed', { 'numbers': true }], 60 | 'max-len': ['warn', { 61 | code: 100, 62 | tabWidth: 2, 63 | ignoreComments: true, 64 | ignoreUrls: true, 65 | ignoreStrings: true, 66 | ignoreTemplateLiterals: true, 67 | ignoreRegExpLiterals: true 68 | }], 69 | 'no-nested-ternary': 'warn', 70 | 'arrow-body-style': 'warn' 71 | }, 72 | }; 73 | -------------------------------------------------------------------------------- /.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | /.vscode 3 | /.idea 4 | /.temp 5 | /coverage 6 | /docker 7 | /webpack 8 | /dist 9 | 10 | [include] 11 | 12 | [libs] 13 | 14 | [lints] 15 | all=warn 16 | 17 | [declarations] 18 | 19 | [options] 20 | emoji=true 21 | include_warnings=true 22 | module.use_strict=true 23 | module.file_ext=.js 24 | module.file_ext=.json 25 | module.name_mapper='^~/\(.*\)$' -> '/src/\1' 26 | 27 | suppress_comment= \\(.\\|\n\\)*\\$FlowFixMe 28 | suppress_comment= \\(.\\|\n\\)*\\$FlowIgnore 29 | suppress_type=$FlowFixMe 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | \.idea 3 | \.vscode 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 doasync 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React `usePromise` hook 2 | 3 | [![NPM Version][npm-image]][npm-url] ![NPM Downloads][downloads-image] [![GitHub issues][issues-image]][issues-url] [![Telegram][telegram-image]][telegram-url] 4 | 5 | [npm-image]: https://img.shields.io/npm/v/use-promise.svg 6 | [npm-url]: https://www.npmjs.com/package/use-promise 7 | [downloads-image]: https://img.shields.io/npm/dw/use-promise.svg 8 | [issues-image]: https://img.shields.io/github/issues/doasync/use-promise.svg 9 | [issues-url]: https://github.com/doasync/use-promise/issues 10 | [telegram-image]: http://i.imgur.com/WANXk3d.png 11 | [telegram-url]: https://t.me/doasync 12 | 13 | An optimized hook for handling promises in React 14 | 15 | It supports `promise.cache` property (or function), which is used by some libraries and prevents unnecessary rerenders. You can use it too if you want 16 | 17 | ### Installation 18 | 19 | ```bash 20 | npm install use-promise 21 | ``` 22 | 23 | or 24 | 25 | ```bash 26 | yarn add use-promise 27 | ``` 28 | 29 | ### Usage 30 | 31 | Wrap a promise in `usePromise` hook and you will get back the following array: `[result, error, pending]`. Use array destructuring to get values that you need: 32 | 33 | ```js 34 | const [company] = usePromise(fetchCompanyPromise) 35 | const [users, usersError, usersLoading] = usePromise(fetchUsersPromise) 36 | ``` 37 | 38 | Do not call an async function inside `usePromise` to get a promise! You will need already prepared promise for this hook. If you don't have a promise, but you want to get it from an async call, then use `useAsyncCall` from [`use-call`](https://www.npmjs.com/package/use-call) package: 39 | 40 | ```js 41 | const [user, userError, userLoading] = useAsyncCall(fetchUser, 120) 42 | ``` 43 | 44 | `useAsyncCall` hook uses `usePromise` from this package to get promise state 45 | 46 | ### Tip 47 | 48 | If you found this hook useful, please star this package on [GitHub](https://github.com/doasync/use-promise) ★ 49 | 50 | ### Author 51 | @doasync 52 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | 2 | const { NODE_ENV } = process.env; 3 | 4 | const presets = [ 5 | ['@babel/preset-env', { 6 | debug: false, 7 | modules: NODE_ENV === 'test' ? 'commonjs' : false, 8 | useBuiltIns: 'usage', 9 | shippedProposals: true, 10 | }], 11 | '@babel/preset-react', 12 | '@babel/preset-flow', 13 | ]; 14 | 15 | const plugins = [ 16 | ['@babel/plugin-proposal-class-properties', { loose: true }], 17 | ['@babel/plugin-syntax-dynamic-import'], 18 | ]; 19 | 20 | module.exports = { presets, plugins }; 21 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable promise/always-return */ 2 | 3 | const { useRef, useState, useEffect } = require('react'); 4 | 5 | const isPromise = x => x !== null && typeof x === 'object' && typeof x.then === 'function'; 6 | const defaultState = [undefined, null, true]; 7 | 8 | const usePromise = (promise) => { 9 | const self = useRef({ state: defaultState }).current; 10 | const [, pushState] = useState(); 11 | 12 | if (promise !== self.promise) { 13 | if (isPromise(promise)) { 14 | self.promise = promise; 15 | const cache = typeof promise.cache === 'function' ? promise.cache() : promise.cache; 16 | self.state = cache ? [cache, null, false] : defaultState; 17 | } else { 18 | throw new Error(`expected a promise but got: ${typeof promise}`); 19 | } 20 | } 21 | 22 | useEffect( 23 | () => { 24 | let isValid = true; 25 | 26 | if (!promise.cache) { 27 | promise 28 | .then((result) => { 29 | self.state = [result, null, false]; 30 | if (isValid) pushState(self.state); 31 | }) 32 | .catch((error) => { 33 | self.state = [undefined, error, false]; 34 | if (isValid) pushState(self.state); 35 | }); 36 | } 37 | 38 | return () => { 39 | self.state = defaultState; 40 | isValid = false; 41 | }; 42 | }, 43 | [promise], 44 | ); 45 | 46 | return self.state; 47 | }; 48 | 49 | module.exports = { 50 | usePromise, 51 | }; 52 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "use-promise", 3 | "description": "usePromise React hook", 4 | "version": "2.0.1", 5 | "author": { 6 | "name": "DoAsync", 7 | "email": "doasync@gmail.com" 8 | }, 9 | "main": "index.js", 10 | "dependencies": { 11 | "react": "^16.8.1" 12 | }, 13 | "devDependencies": { 14 | "@babel/core": "^7.0.0", 15 | "@babel/plugin-proposal-class-properties": "^7.0.0", 16 | "@babel/plugin-syntax-dynamic-import": "^7.0.0", 17 | "@babel/preset-env": "^7.0.0", 18 | "@babel/preset-flow": "^7.0.0", 19 | "@babel/preset-react": "^7.0.0", 20 | "babel-eslint": "^10.0.1", 21 | "babel-jest": "^24.1.0", 22 | "eslint": "^5.5.0", 23 | "eslint-config-airbnb": "^17.1.0", 24 | "eslint-import-resolver-webpack": "^0.11", 25 | "eslint-loader": "^2.1.0", 26 | "eslint-plugin-compat": "^2.6.2", 27 | "eslint-plugin-eslint-comments": "^3.0.1", 28 | "eslint-plugin-html": "^5.0.3", 29 | "eslint-plugin-import": "^2.14.0", 30 | "eslint-plugin-jsx-a11y": "^6.2.1", 31 | "eslint-plugin-node": "^7.0.1", 32 | "eslint-plugin-promise": "^4.0.0", 33 | "eslint-plugin-react": "^7.11.1", 34 | "eslint-plugin-react-hooks": "^1.0.0", 35 | "eslint-plugin-security": "^1.4.0", 36 | "flow-bin": "^0.92.0", 37 | "flow-coverage-report": "^0.6.1", 38 | "flow-typed": "^2.5.1", 39 | "graphql": "^0.13.0", 40 | "jest": "^24.1.0", 41 | "prettier": "^1.16.4", 42 | "react-dom": "^16.8.1", 43 | "react-testing-library": "^5.8.0", 44 | "typescript": "^3.3.3", 45 | "webpack": "^4.29.3" 46 | }, 47 | "repository": { 48 | "type": "git", 49 | "url": "git://github.com/doasync/use-promise.git" 50 | }, 51 | "keywords": [ 52 | "promise", 53 | "future", 54 | "async", 55 | "use", 56 | "hooks", 57 | "react", 58 | "effector" 59 | ], 60 | "license": "MIT" 61 | } 62 | --------------------------------------------------------------------------------