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

new-react-use-form

v2.0.0

Published

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

Downloads

6

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
  • ✅ Strong 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() {
  <FormContext.Provider value={instance}>
    <ChildComponent />
  </FormContext.Provider>;
}

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

/**
 * 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 or all error fields.
 */
form.errors.clear(field: 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 = 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: