### Install use-formspark with NPM or Yarn
Source: https://github.com/formspark/use-formspark/blob/master/README.md
Install the library using either NPM or Yarn package managers.
```bash
# NPM
npm install @formspark/use-formspark
# Yarn
yarn add @formspark/use-formspark
```
--------------------------------
### Handle FormsparkError in Newsletter Subscription
Source: https://context7.com/formspark/use-formspark/llms.txt
Demonstrates how to use the `useFormspark` hook for a newsletter subscription and specifically catch and handle `FormsparkError` instances. It provides examples for different HTTP status codes like 404 and 422.
```tsx
import { useFormspark, FormsparkError } from "@formspark/use-formspark";
const NewsletterForm = () => {
const [submit, submitting] = useFormspark({ formId: "newsletter-xyz" });
const handleClick = async () => {
try {
const response = await submit({ email: "user@example.com" });
console.log("Success:", response);
// response is the parsed JSON returned by Formspark
} catch (error) {
if (error instanceof FormsparkError) {
switch (error.status) {
case 404:
console.error("Form not found. Check your formId.");
break;
case 422:
console.error("Validation error:", error.body);
break;
default:
console.error(`Server error ${error.status}:`, error.body);
}
}
}
};
return (
);
};
```
--------------------------------
### Basic Form Submission with useFormspark
Source: https://github.com/formspark/use-formspark/blob/master/README.md
Use the useFormspark hook to manage form state and submission. Requires a form ID and handles submitting form data.
```tsx
import React, { useState } from "react";
import { useFormspark } from "@formspark/use-formspark";
const ContactForm = () => {
const [submit, submitting] = useFormspark({
formId: "your-form-id"
});
const [message, setMessage] = useState("");
return (
);
};
```
--------------------------------
### Define Args Type for useFormspark
Source: https://context7.com/formspark/use-formspark/llms.txt
The `Args` type is required by `useFormspark` and must include the `formId`. This ID is a segment of your Formspark action URL.
```typescript
import { Args } from "@formspark/use-formspark";
// Type definition:
// type Args = { formId: string };
const args: Args = { formId: "capybara" };
// Corresponds to the action URL: https://submit-form.com/capybara
```
--------------------------------
### useFormspark Hook
Source: https://context7.com/formspark/use-formspark/llms.txt
The primary hook `useFormspark` accepts a configuration object with a `formId` and returns a two-element tuple: an async `submit` function and a `submitting` boolean. The `submitting` flag indicates if an HTTP request is in flight. The `submit` function takes a payload and resolves with the parsed JSON response on success.
```APIDOC
## `useFormspark(args: Args): [submit, submitting]`
### Description
The primary hook. Accepts a configuration object with a `formId` string and returns a two-element tuple: an async `submit` function and a `submitting` boolean. The `submitting` flag is `true` only while the HTTP request is in flight, and is guaranteed to be reset to `false` whether the request succeeds or throws. The `submit` function accepts any `Record` payload and resolves with the parsed JSON response on success.
### Parameters
#### `args` (object)
- **formId** (string) - Required - The unique identifier for your Formspark form.
### Returns
- **submit** (function) - An async function to submit form data. Accepts a payload object and returns a Promise that resolves with the server's JSON response.
- **submitting** (boolean) - A boolean flag indicating if a submission is currently in progress.
```
--------------------------------
### Handle Formspark Errors
Source: https://github.com/formspark/use-formspark/blob/master/README.md
Implement error handling for form submissions using a try-catch block. Catches FormsparkError to access status and response body.
```ts
import { useFormspark, FormsparkError } from "@formspark/use-formspark";
try {
await submit({ message });
} catch (error) {
if (error instanceof FormsparkError) {
console.error(error.status, error.body);
}
}
```
--------------------------------
### Use useFormspark Hook for Contact Form
Source: https://context7.com/formspark/use-formspark/llms.txt
Integrates the `useFormspark` hook into a React component to handle form submissions. It manages input states, submission status, and displays success or error messages. Ensure your `formId` is correctly set.
```tsx
import React, { useState } from "react";
import { useFormspark, FormsparkError } from "@formspark/use-formspark";
const ContactForm = () => {
// formId is the last segment of your Formspark action URL
// e.g. for https://submit-form.com/abc123 the formId is "abc123"
const [submit, submitting] = useFormspark({ formId: "abc123" });
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [message, setMessage] = useState("");
const [status, setStatus] = useState(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setStatus(null);
try {
await submit({ name, email, message });
setStatus("Message sent successfully!");
} catch (error) {
if (error instanceof FormsparkError) {
// error.status => HTTP status code, e.g. 404, 422, 500
// error.body => parsed JSON body or raw text from the server
setStatus(`Error ${error.status}: ${JSON.stringify(error.body)}`);
} else {
setStatus("An unexpected error occurred.");
}
}
};
return (
);
};
export default ContactForm;
```
--------------------------------
### Define SubmitPayload Type for useFormspark
Source: https://context7.com/formspark/use-formspark/llms.txt
The `SubmitPayload` type represents the data object passed to the `submit` function. It can accommodate any form data structure, including custom fields and Formspark-specific options like `_redirect` and `_email`.
```typescript
import { SubmitPayload } from "@formspark/use-formspark";
// Type definition:
// type SubmitPayload = Record;
const payload: SubmitPayload = {
name: "Ada Lovelace",
email: "ada@example.com",
message: "I love React hooks!",
// Any additional fields supported by your Formspark form configuration
_redirect: false,
_email: {
subject: "New contact form submission",
},
};
```
--------------------------------
### FormsparkError Class
Source: https://context7.com/formspark/use-formspark/llms.txt
A custom `Error` subclass thrown by the `submit` function when the Formspark API returns a non-2xx HTTP status. It includes `status` (HTTP status code) and `body` (parsed JSON response or raw text) properties.
```APIDOC
## `FormsparkError`
### Description
A custom `Error` subclass thrown by `submit` when the Formspark API responds with a non-2xx HTTP status. It extends the native `Error` with two additional properties: `status` (the numeric HTTP status code) and `body` (the response body, parsed as JSON when possible, otherwise kept as a raw string). Its `name` is always `"FormsparkError"`.
### Properties
- **status** (number) - The HTTP status code of the error response.
- **body** (any) - The response body from the server, parsed as JSON if possible, otherwise a raw string.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.