You can track the form values with a single useState() hook.
You can use both input onChange event handlers, and form onSubmit event handler to build a component that behaves like you want.
The following is an example React component with hooks you can take as a starting point to manage your state. Please take it as a template and tweak it as needed to fulfill your actual requirement.
const storedData = [
{ id: 1, name: 'apple', city: 'ban' },
{ id: 2, name: 'mango', city: 'hyd' },
]
let nextId = 3
const MyFormComponent = () => {
const initialFormData = { name: '', city: '' }
const [formData, setFormData] = useState(initialFormData)
const clearFormData = () => {
setFormData(initialFormData)
}
const handleOnInputChange = (event) => {
const { value, name } = event.target
// merge previous formData with the new value from input
setFormData({
...formData,
[name]: value,
})
}
const handleOnSubmit = (event) => {
// prevent HTML form default handler (navigation, etc.)
event.preventDefault()
const { name, city } = formData
// OPTIONAL: handle form data validations
if (name === '') {
// no "name" provided
alert('Must specify a name!')
return
}
// input1 "name" and input2 "city" are available in formData
// TODO handle the form data and implement your application logic / update storedData / etc.
// TODO a rough example below, please tweak it to match your requirements
const existingEntryByIndex = storedData.findIndex(
({ name }) => formData.name === name
)
if (existingEntryByIndex >= 0 && formData.city === '') {
// name exists and city value is empty => delete this entry
// NOTE: city value can't be null, because it will be always a string. Maybe, you can use "null" string though.
storedData.splice(existingEntryByIndex, 1)
} else {
// name exists and city not empty, or name is new => add a new city
storedData.push({ id: nextId, name, city })
nextId++
}
// --- end of rough example ---
// OPTIONAL: clear the form values ->
clearFormData()
}
return (
<div className={'my-form-container'}>
<form onSubmit={handleOnSubmit}>
<input
type="text"
name="name"
value={formData.name}
onChange={handleOnInputChange}
/>
<input
type="text"
name="city"
value={formData.city}
onChange={handleOnInputChange}
/>
</form>
</div>
)
For further reference, you can check the React docs to learn about more techniques and ways to handle form inputs, and events.