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

@alfonsobries/react-use-form

v0.3.1

Published

React hook for handling Laravel form requests and validation (for React & React Native)

Downloads

79

Readme

CI

React-use-form

React hook for handling form states, requests, and validation, compatible with React and React Native.

  • ✅ Simple and intuitive API
  • ✅ 100% Test coverage
  • ✅ Strongly typed with TypeScript
  • ✅ Ready for Laravel validation responses
  • ✅ Error handling

Installation

npm install @alfonsobries/react-use-form

Or, as an alternative, use yarn

yarn add @alfonsobries/react-use-form

Quick usage

  1. Import the useForm hook
import useForm from '@alfonsobries/react-use-form';
  1. Initialize your form by passing the form state to the hook function. You can use the form attributes directly to read the state and use the form API to manage the values and the errors.
function MyComponent() {
  const formState = {
    name: 'Alfonso',
    email: '[email protected]',
    rememberMe: false,
  };

  const form = useForm(formState);

  const onSubmit = () => {
    // Submit handling
  };

  return (
    <form onSubmit={onSubmit}>
      <div>
        <label>Name</label>
        <input
          type="text"
          value={form.name}
          onChange={(e) => form.set('name', e.target.value)}
        />
        {form.errors.has('name') && <span>{form.errors.get('name')}</span>}
      </div>

      <button type="submit">Submit</button>
    </form>
  );
}
  1. Use the request methods to send an HTTP request with the form state.
// Submit method (called by the form (see full example above))
const onSubmit = () => {
  // Submit handling
  // you can use `.post`, `.get`, `.delete`, etc.
  form
    .post('https://my-custom-api.test')
    .then((response) => {
      console.log(response.data);
    })
    .catch((error) => {
      console.error(error);
    });
};

Custom axios instance

If needed, you can pass your custom axios instance as the second parameter of the hook

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: { 'X-Custom-Header': 'foobar' },
});

const form = useForm(formState, instance);

// ...
const submitHandler = async () => {
  // Since the custom instance has a baseUrl I can pass a relative path:
  const response = await form.post('relative/path');
};

You can also use the included form context to change the axios instance globally

// Inside the main file
import { FormContext } from '@alfonsobries/react-use-form';

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: { 'X-Custom-Header': 'foobar' },
});

function App() {
  return (
    <FormContext.Provider value={instance}>
      <ChildComponent />
    </FormContext.Provider>
  );
}

Request Configuration ^0.3.1

The RequestConfig interface allows you to customize how the form request is made. This interface has two optional properties:

  • requestConfig: This is an object of type AxiosRequestConfig and allows you to pass any configuration options directly to the Axios request, such as headers, parameters, or timeout settings.
  • keepBusyOnSuccess: This boolean flag, when set to true, keeps the form in a busy state even after a successful request. This can be useful in scenarios where you want to prevent user interaction until a follow-up action is completed.

Example usage:

form.post('/submit', {
  requestConfig: {
    headers: { Authorization: 'Bearer my-token' },
    timeout: 5000,
  },
  keepBusyOnSuccess: true,
});

API

Form API

const form = new Form({ ... })

/**
 * Indicates if the form is busy making an HTTP request to the server.
 */
form.busy: boolean

/**
 * Indicates if the form HTTP request was successful.
 */
form.successful: boolean

/**
 * The validation errors from the server.
 */
form.errors: Errors

/**
 * The upload progress object.
 */
form.progress: { total: number, loaded: number, percentage: number } | undefined

/**
 * Indicates if the form data has been modified from its original state.
 */
form.dirty: boolean

/**
 * Set the value for the attribute
 */
form.set(field: string, fieldValue: any)

/**
 * Submit the form data via an HTTP request.
 */
form.submit(method: string, url: string, config = {})
form.post|patch|put|delete|get(url: string, config = {})

/**
 * Clear the form errors.
 */
form.clear()

/**
 * Reset the form data.
 */
form.reset()

/**
 * Update the form data.
 */
form.update({ ... })

/**
 * Fill the form data.
 */
form.fill({ ... })

Errors API

/**
 * Get all the errors.
 */
form.errors.all()

/**
 * Determine if there is an error for the given field.
 */
form.errors.has(field: string): boolean

/**
 * Determine if there are any errors.
 */
form.errors.any(): boolean

/**
 * Get the first error message for the given field.
 */
form.errors.get(field: string): string|undefined

/**
 * Get all the error messages for the given field.
 */
form.errors.getAll(field: string): string[]

/**
 * Get all the errors in a flat array.
 */
form.errors.flatten(): string[]

/**
 * Clear one, some or all error fields.
 */
form.errors.clear(field: string|string[]|undefined)

/**
 * Set the errors object.
 */
form.errors.set(errors = {})

/**
 * Set a specified error message.
 */
form.errors.set(field: string, message: string)

Examples

React Form (with TypeScript)

import React, { FormEventHandler } from 'react';
import useForm from '@alfonsobries/react-use-form';

type ExampleApiResponse = {
  myString: string;
  myNumber: number;
};

function LoginForm() {
  const form: Form = useForm({
    name: 'Alfonso',
    email: '[email protected]',
    rememberMe: false,
  });

  const onSubmit: FormEventHandler<HTMLFormElement> = (e) => {
    e.preventDefault();

    form
      .post<ExampleApiResponse>('https://my-custom-api.test')
      .then((response) => {
        // `response.data` is typed as `ExampleApiResponse`
        console.log(response.data.myString.charAt(0));
        console.log(response.data.myNumber.toFixed());
      })
      .catch((error) => {
        console.error(error);
      });
  };

  return (
    <form onSubmit={onSubmit}>
      <div>
        <label>Name</label>
        <input
          type="text"
          value={form.name}
          onChange={(e) => form.set('name', e.target.value)}
        />
        {form.errors.has('name') && <span>{form.errors.get('name')}</span>}
      </div>

      <div>
        <label>Email</label>
        <input
          type="text"
          value={form.email}
          onChange={(e) => form.set('email', e.target.value)}
        />
        {form.errors.has('email') && <span>{form.errors.get('email')}</span>}
      </div>

      <div>
        <label>
          <input
            type="checkbox"
            checked={form.rememberMe === true}
            onChange={() => form.set('rememberMe', !form.rememberMe)}
          />
          Remember me
        </label>
      </div>

      <button type="submit">Submit</button>
    </form>
  );
}

export default LoginForm;

React Form (non-typed)

import React from 'react';
import useForm from '@alfonsobries/react-use-form';

function LoginForm() {
  const form = useForm({
    name: 'Alfonso',
    email: '[email protected]',
    rememberMe: false,
  });

  const onSubmit = (e) => {
    e.preventDefault();

    form
      .post('https://my-custom-api.test')
      .then((response) => {
        console.log(response.data.myString.charAt(0));
        console.log(response.data.myNumber.toFixed());
      })
      .catch((error) => {
        console.error(error);
      });
  };

  return (
    <form onSubmit={onSubmit}>
      <div>
        <label>Name</label>
        <input
          type="text"
          value={form.name}
          onChange={(e) => form.set('name', e.target.value)}
        />
        {form.errors.has('name') && <span>{form.errors.get('name')}</span>}
      </div>

      <div>
        <label>Email</label>
        <input
          type="text"
          value={form.email}
          onChange={(e) => form.set('email', e.target.value)}
        />
        {form.errors.has('email') && <span>{form.errors.get('email')}</span>}
      </div>

      <div>
        <label>
          <input
            type="checkbox"
            checked={form.rememberMe === true}
            onChange={() => form.set('rememberMe', !form.rememberMe)}
          />
          Remember me
        </label>
      </div>

      <button type="submit">Submit</button>
    </form>
  );
}

export default LoginForm;

Contribute

Did I save you a few hours of work? Consider: