React onChange with input field & button

Mahesh
JavaScript in Plain English
2 min readOct 1, 2019

--

fig(a): UI component flow

We wanted the component to display the initial render data on load. If the user makes changes by editing then we want to present with an option to SAVE, if the user clicks save then we make POST call and update the save button to be SAVING and disable it, once the update is successful the button label reverted back to SAVE but kept in disable status until the next edit. In short, the button will only be enabled if the input field is dirty.

The main problems are ( i ). Keeping an eye for changing input values & enable/disable the save button. ( ii ). Enable/Disable the save button while dealing with API request.

  1. Exploring onChange for input field

Looking at the code you can see the initial data is displayed when the app is loaded ( i.e Bob ). If the user changes then name to Bobby then the form is dirty and SAVE button is enabled. Great, but the problem with this is onChange gets triggered even when the user changes the name back to Bob ( let say Bobby to Bob ). We need something custom function to validate actual data for change and control the save button.

2. Custom on change for input field & controlling SAVE button

3. Managing button during API call

At last, we need to make sure enabling/disabling button is done when there is no change in data and during API call. I mean, when the user doesn’t really change the data ( though form might be dirty ) we don’t want to enable the SAVE button, also we want to keep the disabled status and update the text from SAVE to SAVING… until the api call is complete. Below is the complete gist.

4. Demo

Finally, “Ease of use may be invisible, but its absence sure isn’t.” — IBM

--

--