Home > OS >  Check if the form is updated in React JS
Check if the form is updated in React JS

Time:08-24

I have a form in my react application which is inside a modal pop up. so when the user closes the pop up i want to check if there is any changes made in the form fields.If so i will show a confirmation modal and if no changes i will close the pop up.

<FormProvider {...methods}>
  <form onSubmit={handleSubmit(submitDetails)}>
    <FormInput
      onChange={handleChange(onChange, value)}
      onBlur={onBlur}
      value={value ?? ""}
      name="name"
    />

    <FormInput
      onChange={handleChange(onChange, value)}
      onBlur={onBlur}
      value={value ?? ""}
      name="age"
    />

    <section className="submit-section">
      <Button onClick={() => checkUnsavedAndClose()}>Cancel</Button>
      <Button type="submit" disabled={!isValid}>
        Save
      </Button>
    </section>
  </form>
</FormProvider>

const checkUnsavedAndClose = () => {
 // if the form is not updated
   closePopUp();
 // if the form is updated
   alertPopup();
}

What is the best approach to validate the entire form irrespective of number of fields in it. i was thinking of checking whether the form is touched or dirty. but i am not sure that it would be the best solution. any inputs will be highly appreciated

CodePudding user response:

Assuming the "handleChange" function is used for all inputs one thing you could do is use it to hold on state a variable for changes

handleChange(onChange, value) {
  value !== originalValue && setState({anyChanges: true}) //or useState and set the state inside the modal 
onChange(value)
}

you could also hold which fields were modified and not save to improve the pop-up message

CodePudding user response:

by creating a boolean changed state. that you can change true/false. And you check the value when you try to close the popup.

const [changed, setChanged] = useState(false);

const handleChange() {
// your code

setChanged(true)

}


const checkUnsavedAndClose = () => {
 if(changed) {
   alertPopup();
} else {
   closePopUp();
   setChanged(false)
}
  • Related