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 { $api, $route, createAction } from "dreamkit";
export const start = $api.title("Start").create(async () => {
await new Promise((resolve) => setTimeout(resolve, 1000));
const id = Date.now();
if (id % 2) throw new Error("Random error");
return id;
});
export default $route
.path("/")
.api({ start })
.create(({ api }) => {
const start = createAction(api.start);
return (
<>
<ul>
<li>state: {start.state}</li>
<li>result: {start.result}</li>
<li>error: {start.error?.message}</li>
</ul>
<button
onClick={start}
disabled={start.running}
children={api.start.title}
/>
<button
onClick={start.abort}
disabled={!start.running}
children="abort"
/>
</>
);
});

Predefined params

import { $api, $route, createAction, Input, s } from "dreamkit";
import { createEffect, createSignal } from "solid-js";
const remove = $api
.title("Remove")
.params({
key: s.title("Key").string(),
})
.create(({ key }) => {
console.log("Received", { key });
});
export default $route
.path("/")
.api({ remove })
.create(({ api }) => {
const [key, setKey] = createSignal("");
const remove = createAction(api.remove).with(() => ({ key: key() }));
createEffect(() => {
if (remove.state === "success") {
setKey("");
remove.clear();
}
});
return (
<>
<p>
<Input
placeholder={api.remove.params.key.options.title}
value={key}
onChange={setKey}
/>
</p>
<button
onClick={remove}
disabled={remove.running}
children={api.remove.title}
/>
</>
);
});