Skip to content

Commit

Permalink
Update model on change (#41)
Browse files Browse the repository at this point in the history
* refactored tests into multiple files

* call update model with hook

* add on change sandbox

* only update model if on change is defined

* use config flag

* default update on

* use nullish

* rollback changes

* added touched object

* rollback changes

* Update simple-delayed-fields.tsx

* renamed fields
  • Loading branch information
leoggonzalez authored Apr 9, 2024
1 parent 7444c15 commit 98822db
Show file tree
Hide file tree
Showing 13 changed files with 1,001 additions and 863 deletions.
7 changes: 5 additions & 2 deletions sandbox-app/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { NestedField } from './nested-field';
import { NestedValidation } from './nested-validation';
import { NullableField } from './nullable-field';
import { ObjectsArray } from './objects-array';
import { OnChange } from './on-change';
import React from 'react';
import ReactDOM from 'react-dom';
import { SimpleArray } from './simple-array';
import { SimpleDelayedFields } from './simple-delayed-fields';
import { SimpleFields } from './simple-fields';
Expand All @@ -17,6 +18,7 @@ const examples = [
'nested-field',
'nullable-field',
'simple-object',
'on-change',
];

function App(): JSX.Element {
Expand All @@ -43,6 +45,7 @@ function App(): JSX.Element {
<NullableField />
<SimpleObject />
<NestedValidation />
<OnChange />
</div>
</>
);
Expand Down
63 changes: 63 additions & 0 deletions sandbox-app/on-change.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import React from 'react';
import { useForm } from '../src';

export function OnChange(): JSX.Element {
const data = React.useRef({
name: 'John Doe',
confirm: false,
});

const { fields, changes, touchedValues, onSubmit, reset } = useForm({
model: data.current,
onSubmit: async ({ model }) => {
data.current = model;
},
onChange: async ({ changes, touchedValues }) => {
data.current = {
...data.current,
...changes,
...touchedValues,
};
},
});

return (
<>
<h2 id="on-change">On Change</h2>
<p>
Changes does not reflect a double toggled boolean state because the
value will be the same as the initial value. We can now use the touched
object to get an updated model with the changes.
</p>

<form onSubmit={onSubmit}>
<label>
<span>Confirm</span>
<input
type="checkbox"
checked={fields.confirm.value}
onChange={(event) => {
fields.confirm.touch();
fields.confirm.onChange(event.target.checked);
}}
/>
</label>
<footer>
<button>Submit</button>
<button onClick={reset} type="button">
Reset
</button>
</footer>
</form>
<h4>Data</h4>
<pre>
{JSON.stringify(
{ data: data.current, changes, touchedValues },
null,
2
)}
</pre>
<a href="#">Back</a>
</>
);
}
Loading

0 comments on commit 98822db

Please sign in to comment.