{"id":16790357,"url":"https://github.com/alfonsobries/react-use-form","last_synced_at":"2025-04-10T23:32:23.189Z","repository":{"id":57681332,"uuid":"476958456","full_name":"alfonsobries/react-use-form","owner":"alfonsobries","description":"React hook for handling Laravel form requests and validation (for React \u0026 React Native)","archived":false,"fork":false,"pushed_at":"2024-08-13T23:17:01.000Z","size":655,"stargazers_count":11,"open_issues_count":0,"forks_count":3,"subscribers_count":3,"default_branch":"main","last_synced_at":"2024-10-29T23:41:47.244Z","etag":null,"topics":["form","laravel","react","react-native"],"latest_commit_sha":null,"homepage":"https://github.com/alfonsobries/react-use-form","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alfonsobries.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"alfonsobries","custom":"https://www.buymeacoffee.com/alfonsobries"}},"created_at":"2022-04-02T05:38:22.000Z","updated_at":"2024-08-13T23:17:05.000Z","dependencies_parsed_at":"2023-01-22T16:45:23.249Z","dependency_job_id":"ed485cc6-87eb-4188-acee-e8b564186a78","html_url":"https://github.com/alfonsobries/react-use-form","commit_stats":{"total_commits":113,"total_committers":1,"mean_commits":113.0,"dds":0.0,"last_synced_commit":"2855541813dac6e5e89faaf70e9bbd4556510c7e"},"previous_names":[],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alfonsobries%2Freact-use-form","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alfonsobries%2Freact-use-form/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alfonsobries%2Freact-use-form/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alfonsobries%2Freact-use-form/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alfonsobries","download_url":"https://codeload.github.com/alfonsobries/react-use-form/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247745100,"owners_count":20988936,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["form","laravel","react","react-native"],"created_at":"2024-10-13T08:29:35.125Z","updated_at":"2025-04-10T23:32:23.168Z","avatar_url":"https://github.com/alfonsobries.png","language":"TypeScript","funding_links":["https://github.com/sponsors/alfonsobries","https://www.buymeacoffee.com/alfonsobries"],"categories":[],"sub_categories":[],"readme":"[![CI](https://github.com/alfonsobries/react-use-form/actions/workflows/test.yaml/badge.svg)](https://github.com/alfonsobries/react-use-form/actions/workflows/test.yaml)\n\n# React-use-form\n\nReact hook for handling form states, requests, and validation, compatible with React and React Native.\n\n- ✅ Simple and intuitive API\n- ✅ 100% Test coverage\n- ✅ Strongly typed with TypeScript\n- ✅ Ready for Laravel validation responses\n- ✅ Error handling\n\n## Installation\n\n```console\nnpm install @alfonsobries/react-use-form\n```\n\nOr, as an alternative, use `yarn`\n\n```console\nyarn add @alfonsobries/react-use-form\n```\n\n## Quick usage\n\n1. Import the `useForm` hook\n\n```jsx\nimport useForm from '@alfonsobries/react-use-form';\n```\n\n2. 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.\n\n```jsx\nfunction MyComponent() {\n  const formState = {\n    name: 'Alfonso',\n    email: 'alfonso@vexilo.com',\n    rememberMe: false,\n  };\n\n  const form = useForm(formState);\n\n  const onSubmit = () =\u003e {\n    // Submit handling\n  };\n\n  return (\n    \u003cform onSubmit={onSubmit}\u003e\n      \u003cdiv\u003e\n        \u003clabel\u003eName\u003c/label\u003e\n        \u003cinput\n          type=\"text\"\n          value={form.name}\n          onChange={(e) =\u003e form.set('name', e.target.value)}\n        /\u003e\n        {form.errors.has('name') \u0026\u0026 \u003cspan\u003e{form.errors.get('name')}\u003c/span\u003e}\n      \u003c/div\u003e\n\n      \u003cbutton type=\"submit\"\u003eSubmit\u003c/button\u003e\n    \u003c/form\u003e\n  );\n}\n```\n\n3. Use the request methods to send an HTTP request with the form state.\n\n```js\n// Submit method (called by the form (see full example above))\nconst onSubmit = () =\u003e {\n  // Submit handling\n  // you can use `.post`, `.get`, `.delete`, etc.\n  form\n    .post('https://my-custom-api.test')\n    .then((response) =\u003e {\n      console.log(response.data);\n    })\n    .catch((error) =\u003e {\n      console.error(error);\n    });\n};\n```\n\n## Custom axios instance\n\nIf needed, you can pass your custom axios instance as the second parameter of the hook\n\n```ts\nconst instance = axios.create({\n  baseURL: 'https://some-domain.com/api/',\n  timeout: 1000,\n  headers: { 'X-Custom-Header': 'foobar' },\n});\n\nconst form = useForm(formState, instance);\n\n// ...\nconst submitHandler = async () =\u003e {\n  // Since the custom instance has a baseUrl I can pass a relative path:\n  const response = await form.post('relative/path');\n};\n```\n\nYou can also use the included form context to change the axios instance globally\n\n```jsx\n// Inside the main file\nimport { FormContext } from '@alfonsobries/react-use-form';\n\nconst instance = axios.create({\n  baseURL: 'https://some-domain.com/api/',\n  timeout: 1000,\n  headers: { 'X-Custom-Header': 'foobar' },\n});\n\nfunction App() {\n  return (\n    \u003cFormContext.Provider value={instance}\u003e\n      \u003cChildComponent /\u003e\n    \u003c/FormContext.Provider\u003e\n  );\n}\n```\n\n## Request Configuration `^0.3.1`\n\nThe `RequestConfig` interface allows you to customize how the form request is made. This interface has two optional properties:\n\n- `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.\n- `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.\n\nExample usage:\n\n```ts\nform.post('/submit', {\n  requestConfig: {\n    headers: { Authorization: 'Bearer my-token' },\n    timeout: 5000,\n  },\n  keepBusyOnSuccess: true,\n});\n```\n\n## API\n\n### Form API\n\n```ts\nconst form = new Form({ ... })\n\n/**\n * Indicates if the form is busy making an HTTP request to the server.\n */\nform.busy: boolean\n\n/**\n * Indicates if the form HTTP request was successful.\n */\nform.successful: boolean\n\n/**\n * The validation errors from the server.\n */\nform.errors: Errors\n\n/**\n * The upload progress object.\n */\nform.progress: { total: number, loaded: number, percentage: number } | undefined\n\n/**\n * Indicates if the form data has been modified from its original state.\n */\nform.dirty: boolean\n\n/**\n * Set the value for the attribute\n */\nform.set(field: string, fieldValue: any)\n\n/**\n * Submit the form data via an HTTP request.\n */\nform.submit(method: string, url: string, config = {})\nform.post|patch|put|delete|get(url: string, config = {})\n\n/**\n * Clear the form errors.\n */\nform.clear()\n\n/**\n * Reset the form data.\n */\nform.reset()\n\n/**\n * Update the form data.\n */\nform.update({ ... })\n\n/**\n * Fill the form data.\n */\nform.fill({ ... })\n\n```\n\n### Errors API\n\n```ts\n/**\n * Get all the errors.\n */\nform.errors.all()\n\n/**\n * Determine if there is an error for the given field.\n */\nform.errors.has(field: string): boolean\n\n/**\n * Determine if there are any errors.\n */\nform.errors.any(): boolean\n\n/**\n * Get the first error message for the given field.\n */\nform.errors.get(field: string): string|undefined\n\n/**\n * Get all the error messages for the given field.\n */\nform.errors.getAll(field: string): string[]\n\n/**\n * Get all the errors in a flat array.\n */\nform.errors.flatten(): string[]\n\n/**\n * Clear one, some or all error fields.\n */\nform.errors.clear(field: string|string[]|undefined)\n\n/**\n * Set the errors object.\n */\nform.errors.set(errors = {})\n\n/**\n * Set a specified error message.\n */\nform.errors.set(field: string, message: string)\n\n```\n\n## Examples\n\n### React Form (with TypeScript)\n\n```tsx\nimport React, { FormEventHandler } from 'react';\nimport useForm from '@alfonsobries/react-use-form';\n\ntype ExampleApiResponse = {\n  myString: string;\n  myNumber: number;\n};\n\nfunction LoginForm() {\n  const form: Form = useForm({\n    name: 'Alfonso',\n    email: 'alfonso@vexilo.com',\n    rememberMe: false,\n  });\n\n  const onSubmit: FormEventHandler\u003cHTMLFormElement\u003e = (e) =\u003e {\n    e.preventDefault();\n\n    form\n      .post\u003cExampleApiResponse\u003e('https://my-custom-api.test')\n      .then((response) =\u003e {\n        // `response.data` is typed as `ExampleApiResponse`\n        console.log(response.data.myString.charAt(0));\n        console.log(response.data.myNumber.toFixed());\n      })\n      .catch((error) =\u003e {\n        console.error(error);\n      });\n  };\n\n  return (\n    \u003cform onSubmit={onSubmit}\u003e\n      \u003cdiv\u003e\n        \u003clabel\u003eName\u003c/label\u003e\n        \u003cinput\n          type=\"text\"\n          value={form.name}\n          onChange={(e) =\u003e form.set('name', e.target.value)}\n        /\u003e\n        {form.errors.has('name') \u0026\u0026 \u003cspan\u003e{form.errors.get('name')}\u003c/span\u003e}\n      \u003c/div\u003e\n\n      \u003cdiv\u003e\n        \u003clabel\u003eEmail\u003c/label\u003e\n        \u003cinput\n          type=\"text\"\n          value={form.email}\n          onChange={(e) =\u003e form.set('email', e.target.value)}\n        /\u003e\n        {form.errors.has('email') \u0026\u0026 \u003cspan\u003e{form.errors.get('email')}\u003c/span\u003e}\n      \u003c/div\u003e\n\n      \u003cdiv\u003e\n        \u003clabel\u003e\n          \u003cinput\n            type=\"checkbox\"\n            checked={form.rememberMe === true}\n            onChange={() =\u003e form.set('rememberMe', !form.rememberMe)}\n          /\u003e\n          Remember me\n        \u003c/label\u003e\n      \u003c/div\u003e\n\n      \u003cbutton type=\"submit\"\u003eSubmit\u003c/button\u003e\n    \u003c/form\u003e\n  );\n}\n\nexport default LoginForm;\n```\n\n### React Form (non-typed)\n\n```jsx\nimport React from 'react';\nimport useForm from '@alfonsobries/react-use-form';\n\nfunction LoginForm() {\n  const form = useForm({\n    name: 'Alfonso',\n    email: 'alfonso@vexilo.com',\n    rememberMe: false,\n  });\n\n  const onSubmit = (e) =\u003e {\n    e.preventDefault();\n\n    form\n      .post('https://my-custom-api.test')\n      .then((response) =\u003e {\n        console.log(response.data.myString.charAt(0));\n        console.log(response.data.myNumber.toFixed());\n      })\n      .catch((error) =\u003e {\n        console.error(error);\n      });\n  };\n\n  return (\n    \u003cform onSubmit={onSubmit}\u003e\n      \u003cdiv\u003e\n        \u003clabel\u003eName\u003c/label\u003e\n        \u003cinput\n          type=\"text\"\n          value={form.name}\n          onChange={(e) =\u003e form.set('name', e.target.value)}\n        /\u003e\n        {form.errors.has('name') \u0026\u0026 \u003cspan\u003e{form.errors.get('name')}\u003c/span\u003e}\n      \u003c/div\u003e\n\n      \u003cdiv\u003e\n        \u003clabel\u003eEmail\u003c/label\u003e\n        \u003cinput\n          type=\"text\"\n          value={form.email}\n          onChange={(e) =\u003e form.set('email', e.target.value)}\n        /\u003e\n        {form.errors.has('email') \u0026\u0026 \u003cspan\u003e{form.errors.get('email')}\u003c/span\u003e}\n      \u003c/div\u003e\n\n      \u003cdiv\u003e\n        \u003clabel\u003e\n          \u003cinput\n            type=\"checkbox\"\n            checked={form.rememberMe === true}\n            onChange={() =\u003e form.set('rememberMe', !form.rememberMe)}\n          /\u003e\n          Remember me\n        \u003c/label\u003e\n      \u003c/div\u003e\n\n      \u003cbutton type=\"submit\"\u003eSubmit\u003c/button\u003e\n    \u003c/form\u003e\n  );\n}\n\nexport default LoginForm;\n```\n\n## Contribute\n\nDid I save you a few hours of work? Consider:\n\n- 💵 [Sponsoring my open source work](https://github.com/sponsors/alfonsobries)\n- ⭐ [Nominating me as a GitHub Star](https://stars.github.com/nominate/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falfonsobries%2Freact-use-form","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falfonsobries%2Freact-use-form","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falfonsobries%2Freact-use-form/lists"}