Skip to content

Commit

Permalink
Fix Svelte's useForm helper (inertiajs#1610)
Browse files Browse the repository at this point in the history
* fixes for svelte's useForm helper

* fix useForm reset function

* make data default after successful submit request
  • Loading branch information
edgars-vasiljevs authored Aug 9, 2023
1 parent 2adfa2c commit ea6a634
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
1 change: 1 addition & 0 deletions packages/svelte/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
},
"dependencies": {
"@inertiajs/core": "1.0.9",
"lodash.clonedeep": "^4.5.0",
"lodash.isequal": "^4.5.0"
}
}
16 changes: 9 additions & 7 deletions packages/svelte/src/useForm.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { router } from '@inertiajs/core'
import isEqual from 'lodash.isequal'
import cloneDeep from 'lodash.clonedeep'
import { writable } from 'svelte/store'

function useForm(...args) {
const rememberKey = typeof args[0] === 'string' ? args[0] : null
const data = (typeof args[0] === 'string' ? args[1] : args[0]) || {}
const restored = rememberKey ? router.restore(rememberKey) : null
let defaults = data
let defaults = cloneDeep(data)
let cancelToken = null
let recentlySuccessfulTimeoutId = null
let transform = (data) => data
Expand All @@ -22,7 +23,7 @@ function useForm(...args) {
processing: false,
setStore(key, value) {
store.update((store) => {
return Object.assign({}, store, typeof key === 'string' ? { [key]: value } : key)
return Object.assign(store, typeof key === 'string' ? { [key]: value } : key)
})
},
data() {
Expand All @@ -38,24 +39,25 @@ function useForm(...args) {
},
defaults(key, value) {
if (typeof key === 'undefined') {
defaults = Object.assign(defaults, this.data())
defaults = Object.assign(defaults, cloneDeep(this.data()))

return this
}

defaults = Object.assign(defaults, value ? { [key]: value } : key)
defaults = Object.assign(defaults, cloneDeep(value ? { [key]: value } : key))

return this
},
reset(...fields) {
let clonedDefaults = cloneDeep(defaults)
if (fields.length === 0) {
this.setStore(defaults)
this.setStore(clonedDefaults)
} else {
this.setStore(
Object.keys(defaults)
Object.keys(clonedDefaults)
.filter((key) => fields.includes(key))
.reduce((carry, key) => {
carry[key] = defaults[key]
carry[key] = clonedDefaults[key]
return carry
}, {}),
)
Expand Down

0 comments on commit ea6a634

Please sign in to comment.