Back to Blog
What is dirty?
When a user fills up the form without completely filling up all fields and leaves either deliberately or accidentally. We call that state dirty.
I did not know myself until we worked on a project where we had a lot of forms.
You can either fill up a new form or edit an existing form.
So how do you determine if your form is dirty or not?
First, we have to maintain 2 states.
Initial State and Current State
If a user is trying to close the browser or move to another page, We need to warn them that they have not saved their form.
Well you have to compare the initial state Vs Final State
You have to compare the object values of the initial state vs the final state
Some libraries can help you deep compare.
Some devs use JSON.stringify to convert form value into a string and compare that
Some use deep compare libraries like Lodash and Ramda. They provide utilities right out of the box to compare
Some form libraries like Formik provide an API Reference value that automatically tells you whether their form is dirty or not.