Skip to content

Commit

Permalink
Ensure event listener is only bound once (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
timacdonald authored Jun 5, 2023
1 parent 1018801 commit 13fe572
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
3 changes: 2 additions & 1 deletion packages/react-inertia/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
"node": ">=14"
},
"peerDependencies": {
"@inertiajs/react": "^1.0.0"
"@inertiajs/react": "^1.0.0",
"react": "^18.0.0"
},
"dependencies": {
"laravel-precognition": "^0.2.0",
Expand Down
31 changes: 19 additions & 12 deletions packages/react-inertia/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { Config, NamedInputEvent, RequestMethod, SimpleValidationErrors, toSimpleValidationErrors, ValidationConfig, ValidationErrors } from 'laravel-precognition'
import { useForm as usePrecognitiveForm } from 'laravel-precognition-react'
import { useForm as useInertiaForm } from '@inertiajs/react'
import { useRef } from 'react'

export const useForm = <Data extends Record<string, unknown>>(method: RequestMethod, url: string, inputs: Data, config: ValidationConfig = {}): any => {
const booted = useRef<boolean>(false)

/**
* The Inertia form.
*/
Expand All @@ -13,18 +16,6 @@ export const useForm = <Data extends Record<string, unknown>>(method: RequestMet
*/
const precognitiveForm = usePrecognitiveForm(method, url, inputs, config)

/**
* Setup event listeners.
*/
precognitiveForm.validator().on('errorsChanged', () => {
inertiaClearErrors()

inertiaSetError(
// @ts-expect-error
toSimpleValidationErrors(precognitiveForm.validator().errors())
)
})

/**
* The Inertia submit function.
*/
Expand All @@ -50,6 +41,22 @@ export const useForm = <Data extends Record<string, unknown>>(method: RequestMet
*/
const inertiaSetData = inertiaForm.setData.bind(inertiaForm)

if (! booted.current) {
/**
* Setup event listeners.
*/
precognitiveForm.validator().on('errorsChanged', () => {
inertiaClearErrors()

inertiaSetError(
// @ts-expect-error
toSimpleValidationErrors(precognitiveForm.validator().errors())
)
})

booted.current = true
}

/**
* Patch the form.
*/
Expand Down

0 comments on commit 13fe572

Please sign in to comment.