In my React/ Redux app, I have a text input with its default value retrieved via Ajax call. User can edit the default value in the input, and then submit the updated value by clicking on a 'submit' link. I'm struggling with using either uncontrolled or controlled inputs for this.
Any suggestions what I can do here?
As the docs say, the defaultValue
is only useful at the initial render. So if you want to use defaultValue
you have to delay the rendering of that particular component until after the data is loaded. Consider putting a loading gif (or something similar) in place of the form for the AJAX call.
I don't think the second way - using value
and updating with onChange
- is as bad as you say; it's generally how I write my forms. However, the real problem here is once again the delayed loading. By the time the initial value loads in, a user may already have filled in that input, only to see it overwritten with the received AJAX value. Not fun.
The best way in my view is simply to not use AJAX. Append your initial data to the webpage itself as a global variable. This may sound like an anti-pattern but you only ever read the global once, and it saves you cost of an AJAX request. In Redux there's a convenient way of doing this which I've documented here and here.