I'm stuck with passing data returned from a mutation to handle form validation in Reactjs. This pattern is not limited to only form validation but to other components which share similar requirements where something is mutated/queried and the response data is used to update the UI only.
Concept:
<LoginForm/>
component renders the login form and commits the loginMutation
with form data. Validation happens on the backend, if there are any errors catched by the validation the mutation will resolve with field errors
which contains key-value pairs where key represents the form field and value describes what's wrong with the value. The idea is to pass the errors
object to the <LoginForm/>
so that the component can render/update to display the errors in the UI.
errors: {
username: "Username must not be empty",
password: "Password must not be empty"
}
Challenge:
In what way should resolved data (errors
) be passed to the <LoginForm/>
? The most straightforward, hammer-nail method would be to pass a callback function to the loginMutation
from the <LoginForm/>
and call it inside of the onComplete()
with the response object. Something like this:
onCompleted: (response, errors) => { setLoginFormState(resonse.errors) }
Then in the <LoginForm/>
there would be
setLoginFormState(validationState){
this.setState({errors: validationState })
}
And finally we can update the UI accordingly in the <LoginForm/>
like this
render(){
const { errors } = this.state;
const usernameClass = errors.username ? 'danger' : 'primary';
const passwordClass = errors.password ? 'danger' : 'primary';
return (
<div>
<input name="username" className={usernameClass} />
<input name="username" className={passwordClass} />
</div>
)
}
I'm searching for a less imperative approach that produces less spaghetti.
Also I'm looking forward to the announced schema extensions feature which is currently missing docs. It seems as if it's purpose is to solve this problem by allowing us to mix local state(UI state for instance) with the persistent data fetched from the queries/mutations.