DataHooks
useAction
A write (invite, approve, save settings): run(input) sends it through the client (CSRF and all), keeps the message and 422 field errors as state for the form, and calls onDone on success. Guarded against a double submit. Takes a function (input, client) => Promise<R> or a { method, url, body? } spec.
import { useAction } from '@ergasti/bricks';Examples
Save with field errors
run resolves to { ok: true, data } or { ok: false, … } and never rejects on an HTTP failure; a 422's field errors land in fieldErrors keyed by field, other failures in error in the language of the page. The pretend server wants 4 characters or more.
Code
import { useState } from 'react';
import { Button, DataProvider, FormField, createHttpClient, useAction } from '@ergasti/bricks';
import { demoServer } from './sample-data';
const client = createHttpClient({
baseUrl: '/api',
fetch: demoServer({
'POST /api/codes': ({ body }) => {
const code = String((body as { code?: string }).code ?? '');
return code.length < 4 ? { status: 422, body: { message: 'Invalid.', errors: { code: ['Use at least 4 characters.'] } } } : { id: 1, code };
},
}, 600),
});
function Form() {
const [code, setCode] = useState('KA');
const [done, setDone] = useState('');
const save = useAction<{ code: string }, { id: number; code: string }>({ method: 'POST', url: '/codes' }, { onDone: (data) => setDone(`Saved ${data.code}`) });
return (
<form onSubmit={(event) => { event.preventDefault(); setDone(''); void save.run({ code }); }} style={{ maxWidth: 320 }}>
<FormField label="Coupon code" error={save.fieldErrors.code}><input value={code} onChange={(e) => setCode(e.target.value)} /></FormField>
{save.error && <p role="alert">{save.error}</p>}
<Button variant="rasp" disabled={save.pending} type="submit">{save.pending ? 'Saving…' : 'Save'}</Button>
{done && <p>{done}</p>}
</form>
);
}
function Save() {
return <DataProvider client={client}><Form /></DataProvider>;
}Signature
function useAction<I, R>(action: ActionFn<I, R> | ActionSpec<I>, options?: ActionOptions<I, R>): ActionState<I, R>Parameters
Prop
Type
Returns
ActionState<I, R>
Related
useDataLanguage · useHttpClient · DataProvider · useDebouncedCallback · useDrawerResource · useHashState
Source
src/data/useAction.ts (line 100) on GitHub.