Skip to content

Commit 13fe572

Browse files
authored
Ensure event listener is only bound once (#9)
1 parent 1018801 commit 13fe572

File tree

2 files changed

+21
-13
lines changed

2 files changed

+21
-13
lines changed

packages/react-inertia/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@
2828
"node": ">=14"
2929
},
3030
"peerDependencies": {
31-
"@inertiajs/react": "^1.0.0"
31+
"@inertiajs/react": "^1.0.0",
32+
"react": "^18.0.0"
3233
},
3334
"dependencies": {
3435
"laravel-precognition": "^0.2.0",

packages/react-inertia/src/index.ts

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
import { Config, NamedInputEvent, RequestMethod, SimpleValidationErrors, toSimpleValidationErrors, ValidationConfig, ValidationErrors } from 'laravel-precognition'
22
import { useForm as usePrecognitiveForm } from 'laravel-precognition-react'
33
import { useForm as useInertiaForm } from '@inertiajs/react'
4+
import { useRef } from 'react'
45

56
export const useForm = <Data extends Record<string, unknown>>(method: RequestMethod, url: string, inputs: Data, config: ValidationConfig = {}): any => {
7+
const booted = useRef<boolean>(false)
8+
69
/**
710
* The Inertia form.
811
*/
@@ -13,18 +16,6 @@ export const useForm = <Data extends Record<string, unknown>>(method: RequestMet
1316
*/
1417
const precognitiveForm = usePrecognitiveForm(method, url, inputs, config)
1518

16-
/**
17-
* Setup event listeners.
18-
*/
19-
precognitiveForm.validator().on('errorsChanged', () => {
20-
inertiaClearErrors()
21-
22-
inertiaSetError(
23-
// @ts-expect-error
24-
toSimpleValidationErrors(precognitiveForm.validator().errors())
25-
)
26-
})
27-
2819
/**
2920
* The Inertia submit function.
3021
*/
@@ -50,6 +41,22 @@ export const useForm = <Data extends Record<string, unknown>>(method: RequestMet
5041
*/
5142
const inertiaSetData = inertiaForm.setData.bind(inertiaForm)
5243

44+
if (! booted.current) {
45+
/**
46+
* Setup event listeners.
47+
*/
48+
precognitiveForm.validator().on('errorsChanged', () => {
49+
inertiaClearErrors()
50+
51+
inertiaSetError(
52+
// @ts-expect-error
53+
toSimpleValidationErrors(precognitiveForm.validator().errors())
54+
)
55+
})
56+
57+
booted.current = true
58+
}
59+
5360
/**
5461
* Patch the form.
5562
*/

0 commit comments

Comments
 (0)