Skip to content

Commit 60cc1bd

Browse files
committed
Fix deep clone for forms with nested objects
1 parent 280e244 commit 60cc1bd

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "laravel-form-js",
3-
"version": "1.0.2",
3+
"version": "1.0.3",
44
"description": "A javascript representation of a form",
55
"main": "dist/Form.js",
66
"scripts": {

src/Form.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ class Form {
1717
*/
1818
constructor(data, method = 'post', clearAfterResponse = false) {
1919
this.originalData = data;
20-
Object.assign(this, data);
20+
Object.assign(this, JSON.parse(JSON.stringify(data)));
2121
this.method = method;
2222
this.clearAfterResponse = clearAfterResponse;
2323
this.errors = new FormErrors();
@@ -39,7 +39,7 @@ class Form {
3939
* @return {void}
4040
*/
4141
reset() {
42-
Object.assign(this, this.originalData);
42+
Object.assign(this, JSON.parse(JSON.stringify(this.originalData)));
4343
this.errors.clear();
4444
}
4545

tests/form.test.js

+9
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,15 @@ test('can reset the form data to its original data state', () => {
2828
expect(form.name).toBe('test');
2929
});
3030

31+
test('if the original data has an object it doesnt change the original data', () => {
32+
let form = Form.makeFrom({name: {text: 'name'}});
33+
form.name.text = 'new name';
34+
expect(form.name).toEqual({text: 'new name'});
35+
expect(form.originalData.name).toEqual({text: 'name'});
36+
form.reset();
37+
expect(form.name).toEqual({text: 'name'});
38+
});
39+
3140
test('can change the form http method', () => {
3241
let form = Form.makeFrom({name: 'test'});
3342
form.name = 'new name';

0 commit comments

Comments
 (0)