Auto updating field with React


#1

Hey,
I was building a form with React today and I came across this problem. In React, inputs are treated as these controlled components so if the input elements get’s initialized with a value, React doesn’t allow it to be changed visually. The trick is to add an onChange handler, update the state and render the component using the state values.

So, the question is, if I want the form to auto update my database, should I fire a method from the onChange handler so the props to cause the component to update or should I first set the state, mutate the state and then mutate the database when the state changes???

Thanks.


#2

Hello @fardeemmunir:

the onChange method is only for your input component. If you mutate your database from there you will be mutating de database on every key stroke.
It is more convenient call the database mutation from another method in your component, for example you could create a save method and call that method with a save button in your form, and from the save method you can mutate your database with your state component.

Hope that help.