Skip to content

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
octet-stream committed Feb 7, 2020
0 parents commit a595372
Show file tree
Hide file tree
Showing 7 changed files with 181 additions and 0 deletions.
Empty file added .editorconfig
Empty file.
13 changes: 13 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports = {
"env": {
"browser": true
},
// "plugins": [
// "ava",
// "markdown"
// ],
"extends": [
"@octetstream",
// "plugin:ava/recommended"
]
}
17 changes: 17 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
.DS_Store
node_modules
.nyc_output
coverage
yarn-error.log

test
coverage
.codecov

/.editorconfig
/.eslintrc.json
/.huskyrc.json
/.lintstagedrc
/.travis.yml
/yarn.lock
/test.mjs
21 changes: 21 additions & 0 deletions license
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2020 Nick K.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
20 changes: 20 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "use-suspender",
"version": "0.1.0",
"description": "Execute asyncronous actions with React.Suspense",
"main": "use-suspense.js",
"repository": "[email protected]:octet-stream/use-suspender.git",
"author": "octet-stream <[email protected]>",
"license": "MIT",
"private": false,
"devDependencies": {
"@octetstream/eslint-config": "4.0.0",
"ava": "3.2.0",
"eslint": "6.8.0",
"husky": "4.2.1",
"lint-staged": "10.0.7"
},
"dependencies": {
"nanoid": "^2.1.11"
}
}
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# use-suspender
109 changes: 109 additions & 0 deletions use-suspender.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
const nanoid = require("nanoid")

const isObject = value => typeof value === "object" && value !== null

const isFunction = value => typeof value === "function"

// const replacer = value => isFunction(value) ? String(value) : value

function createSuspender() {
const cache = new Map()
const base = nanoid()

/**
* Executes given suspender function then throws its Promise
* to await and consume its result with React.Suspense.
*
* EXPERIMENTAL!!!
*
* @param {string | {[key: string]: any}} id
* @param {() => Promise<any>} suspender
* @param {Array<any>} [args = []]
*
* @return {any}
*
* @throws {Promise} A promise will be thrown when no suspender with
* such ID found in cache.
*
* @throws {Error} if suspender's Promise has been rejected with an error
*/
function useSuspender(id, suspender, args = []) {
if (suspender == null) {
return undefined
}

if (!id) {
throw new Error("Suspender ID is required.")
}

if (!isFunction(suspender)) {
throw new TypeError("Expected suspender to be a function.")
}

id = JSON.stringify({
...isObject(id) ? id : {id: String(id)}, base
})

// Try to resolve a result of an operation if found in cache
if (cache.has(id)) {
const {result, error, state, ...operation} = cache.get(id)

if (state === "rejected") {
// Probably I should not clean the cache on error
// because react continues to call useSuspender again and again
// cache.delete(id)

throw error
}

// Remove entry from the cache then return the result
if (state === "resolved") {
// NOTE: I think that cache management probably must be reconsidered
// due to the fact of how such early operation removal might affect
// on a further Suspense-dependent components re-renders.
// I almost thing that the closest Suspense is up the component
// that called this function, React may call the component again
// which will cause unnecessary operation's runs.
cache.delete(id)

return result
}

// Be careful to use this hook when something in a component may throw an
// error. I probably must put some error boundary to prevent infinite
// re-renders in such use cases.

// If there's no result neither error then just throw the operation
// again since we probably still waiting for the result
throw operation.suspender
}

const operation = {
error: null,
result: null,
state: "pending",
suspender: Promise.resolve(suspender(...args))
.then(result => {
operation.result = result
operation.state = "resolved"
})

.catch(error => {
operation.error = error
operation.state = "rejected"
})
}

// Cache the operation
cache.set(id, operation)

// Notify React.Suspense
throw operation.suspender
}

return useSuspender
}

module.exports = createSuspender()
module.exports.useSuspender = module.exports
module.exports.createSuspender = createSuspender

0 comments on commit a595372

Please sign in to comment.