JS Helpers
Introduction
Astro forms ship with some utility functions to handle forms. Some functionality works by sending the script to the client and running it there.
You can access them via Astro.locals.forms
.
Controllers
class FormsReact { scriptToRun: string; overrideResponse: Response | null;
// server side redirect redirect(location: string, status?: ValidRedirectStatus): void; updateSearchParams(): { search: URLSearchParams; redirect(status?: ValidRedirectStatus): void; }; updateOneSearchParam(key: string, value?: string, status?: ValidRedirectStatus): void;
// client side redirect redirectTimeoutSeconds(location: string, timeoutSec = 2): void;
alert(message: string): void; consoleLog(...messages: any[]): void; console(type: keyof Console, ...messages: any[]): void; callFunction(func: string, ...args: any[]): void;}
Example
---import { Bind, BindForm, BButton, BInput } from "@astro-utils/forms/forms.js";import Layout from "../layouts/Layout.astro";
type Form = { name: string; age: number;}
const form = Bind<Form>();
let showSubmitText: string;function formSubmit(){ showSubmitText = `You name is ${form.name}, you are ${form.age} years old. `;
// Redirect to home page after 2 seconds Astro.locals.forms.redirectTimeoutSeconds('/');}---<Layout> <BindForm bind={form}> {showSubmitText}
<h4>What you name*</h4> <BInput type="text" name="name" maxlength={20} required/>
<h4>Enter age*</h4> <BInput type="int" name="age" min={10} required/>
<BButton onClick={formSubmit} whenFormOK>Submit</BButton> </BindForm></Layout>
Throw Response
If you want to throw a response from the server.
Meaning you in a nested function and you encore an error and you want to override an response and abort the current page execution.
You can use the ThrowOverrideResponse
class.
new ThrowOverrideResponse(response?: Response, message?: string)
Example
import { ThrowOverrideResponse } from '@astro-utils/forms/forms.js';
throw new ThrowOverrideResponse(new Response('Unauthorized', { status: 401 }));
Edge case:
- If no
Response
is provided, will be use the response stored inlocals.forms.overrideResponse
. - If no
Response
is stored inlocals.forms.overrideResponse
, will be return the message with error code 500.
Edge case example
import { ThrowOverrideResponse } from '@astro-utils/forms/forms.js';
Astro.locals.forms.redirect('/login');throw new ThrowOverrideResponse();
Or you can just pass an error message:
throw new ThrowOverrideResponse(null, 'Unauthorized');