Skip to content

Commit 44c65a5

Browse files
committed
add use async effect
1 parent ad6597e commit 44c65a5

File tree

4 files changed

+34
-2
lines changed

4 files changed

+34
-2
lines changed

package.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "@atomico/kit",
33
"description": "Series of utilities in hooks format to extend the operation of Atomico",
4-
"version": "2.3.0",
4+
"version": "2.4.0",
55
"type": "module",
66
"exports": {
77
"./use-child-nodes": "./src/use-child-nodes/use-child-nodes.js",
@@ -10,7 +10,8 @@
1010
"./use-render": "./src/use-render/use-render.js",
1111
"./use-router": "./src/use-router/use-router.js",
1212
"./use-slot": "./src/use-slot/use-slot.js",
13-
"./use-parent": "./src/use-parent/use-parent.js"
13+
"./use-parent": "./src/use-parent/use-parent.js",
14+
"./use-async-effect": "./src/use-async-effect/use-async-effect.js"
1415
},
1516
"typings": "*.d.ts",
1617
"editable": "https://github.com/atomicojs/atomico-kit/tree/master",
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { useEffect } from "atomico";
2+
/**
3+
*
4+
* @param {()=>Promise<()=>any|void>} effect
5+
* @param {Array<any>} [args]
6+
*/
7+
export function useAsyncEffect(effect, args) {
8+
useEffect(() => {
9+
const task = Promise.resolve(args).then(effect);
10+
return () => task.then((collector) => collector());
11+
}, args);
12+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { expect } from "@esm-bundle/chai";
2+
import { createHooks } from "atomico/test-hooks";
3+
import { useAsyncEffect } from "./use-async-effect.js";
4+
5+
it("useAsyncEffect", (done) => {
6+
const hooks = createHooks();
7+
8+
function load() {
9+
// done only completes at the end of the useEffect loop
10+
useAsyncEffect(async () => done);
11+
}
12+
13+
hooks.load(load);
14+
// mounted effect
15+
hooks.cleanEffects()();
16+
// unmounted effect
17+
hooks.cleanEffects(true)();
18+
});

use-async-effect.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { useAsyncEffect } from "./src/use-async-effect/use-async-effect.js";

0 commit comments

Comments
 (0)