next-server-action-hook
v2.0.0
Published
A React hook for handling Next.js server actions on the client side with built-in loading and error states.
Downloads
31
Readme
Next.js Server Action Hook
This package offers a React hook for managing server actions in a Next.js client-side environment. It leverages the useTransition hook for efficient loading state and error management.
Playground
https://codesandbox.io/p/devbox/next-js-server-action-hook-y32wh8?file=%2Fapp%2Fform.tsx%3A20%2C26
Installation
npm install next-server-action-hook
or
yarn add next-server-action-hook
Usage
Showcase of handling a form submission with a server action
// page.ts
import Form from "./form";
const FormPage = () => {
const handleSubmit = async (formData: FormData) => {
"use server";
const name = formData.get("name");
// validation and error example
if (!name) {
throw new Error("Name is required");
}
// your spot to handle the server stuff ...
return name as string;
};
return <Form action={handleSubmit} />;
};
export default FormPage;
// form.tsx (client)
"use client";
import useServerAction from "next-server-action-hook";
const Form = ({
action,
}: {
action: (formData: FormData) => Promise<string>;
}) => {
const [run, { error, hasError, data: name }, clearError] =
useServerAction(action);
return (
<>
{isLoading && <div>Loading...</div>}
{hasError && <div>Ooops something went wrong</div>}
{name && <div>Hey {name}!</div>}
<h1>Form</h1>
<form action={run}>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
name="name"
onChange={() => clearError()}
/>
<button type="submit">Submit</button>
</form>
</>
);
};
export default Form;
In the given example, useServerAction
is utilized to manage the handleSubmit
server action.
The run
function, when invoked it initiates the states isLoading
, hasError
, and data
- are dynamically updated based on the status and outcome of the promise operation,
providing real-time feedback that can be used to control the rendering of the component.
API
useServerAction(action: () => Promise<any>): [
run: (...args: any[]) => Promise<{ data?: any; }>,
state: { isLoading: boolean; hasError?: boolean; data?: any },
clearError: () => void
]
action
: The server action to handle. This should be a function that returns a Promise.run
: A function that calls the server action with the provided arguments and returns a Promise that resolves to an object with data property.state
: An object withisLoading
,hasError
, anddata
properties.clearError
: A function that clears the error state.
Updates
- to v2.0.0 breaking
run
now returns an object with adata
property.- as nextjs production build doesn't expose the error object, the
hasError
property is now used to determine if an error occurred.
- to v1.2.0 breaking
loading
is nowisLoading
.clearError
is now the 3rd item in the returned array.
License
MIT