Skip to content

createAction

Description

Utility to create actions and control them by signals in a safe way.

It is not strictly necessary to use createAction to work with promises (e.g. fetch), but it is recommended, since it allows you to control their activation and monitoring.

Import

import { createAction } from "dreamkit";

Definition

declare const createAction: (cb: (...args: any[]) => any) => {
with: {
(input: () => any): any;
(...args: any[]): any;
};
readonly id: number;
readonly result: any | undefined;
readonly running: boolean;
readonly error: Error | undefined;
readonly state: "idle" | "running" | "success" | "error";
clear: () => void;
abort: () => void;
};

Examples

Basic usage

import { $route, createAction } from "dreamkit";
export default $route.path("/").create(() => {
const start = createAction(
() =>
new Promise<number>((resolve) => {
setTimeout(() => resolve(Date.now()), 1000);
}),
);
return (
<>
<p>{start.result}</p>
<button onClick={start} disabled={start.running}>
Start
</button>
</>
);
});

Predefined params

import { createAction, Input } from "dreamkit";
import { createEffect, createSignal } from "solid-js";
function remove(key: string) {
console.log("key removed", key);
}
export default function App() {
const [id, setKey] = createSignal("");
const $remove = createAction(remove).with(() => id());
createEffect(() => $remove.state === "success" && $remove.clear());
return (
<>
<Input value={id} onChange={setKey} />
<button onClick={$remove} disabled={$remove.running}>
Remove
</button>
</>
);
}