1.0.3 • Published 2 years ago

use-basin v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Basin React Hook

A simple React hook for handling Basin AJAX forms.

Installation

Install the package:

npm i -D use-basin

Note: a React version above 16.8.3 must be installed as a peer dependency.

Usage

Create a form that will submit to Basin using AJAX:

import useBasin from 'use-basin';

const Form = () => {
  const [state, submit] = useBasin('<form-id>');
  return <form onSubmit={submit}>{/*  inputs... */}</form>;
};

You can also create your own onSubmit handlers for custom error checking or other functionality:

const onSubmit = (e) => {
  e.preventDefault();
  const data = new FormData(e.target);
  console.log(data.get('name'));
  // Be sure to call the submit function to actually
  // submit the form.
  submit(e);
};

You can also use the returned state object for loaders and error handling:

import useBasin from 'use-basin';

const Form = () => {
  const [{ pending, error, submitted }, submit] = useBasin('<form-id>');
  if (pending) return <div>Submitting...</div>;
  if (error) return <div>Something went wrong =(</div>;
  if (submitted) return <div>Thanks for submitting our form!</div>;
  return <form onSubmit={submit}>{/*  inputs... */}</form>;
};

State Variables

The following variables are returned in an object as the first value in the array:

NameDescriptionType
SubmittedThe form has been submittedboolean
PendingA POST request has started but not completed.boolean
ErrorThe most recent POST request failed.boolean