I want to create a form to save some form of data model in a database.
Let's say I have a class:
export default class Model {
constructor(model = {}) {
this.x = model.x || '';
this.y = model.y || '';
}
save() {
// code to save 'this' to database
}
}
And a component:
import { React, useState } from 'react';
export const ModelForm = () => {
const [model, setModel] = useState(new Model());
const handleInputChange = (event) => {
const target = event.target;
setModel({ ...model, [target.name]: target.value });
};
const handleSubmit = (event) => {
event.preventDefault();
const modelObject = new Model(model);
modelObject.save();
};
return (
<form onSubmit={handleSubmit}>
<input type='text' name='x' value={model.x} onChange={handleInputChange} />
<input type='text' name='y' value={model.y} onChange={handleInputChange} />
<button type='submit'>Submit</button>
</form>
);
};
This thing is currently working, but I have a question.
Every time I do setModel, I have to destructure the model object and change the value accordingly. Since I destructure it, when I am submitting the form, the object in the component is no longer a Model object, but a simple javascript Object. So, as you can see, I have to create a new one to use save() on it.
Is my approach good or there is a better way to do it?
Also, is it a good practice to use ES6 classes in useState? Are there any downfalls?