npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

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 with isLoading, hasError, and data properties.
  • clearError: A function that clears the error state.

Updates

  • to v2.0.0 breaking
    • run now returns an object with a data 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 now isLoading.
    • clearError is now the 3rd item in the returned array.

License

MIT