So let’s work on lifting the state up. Currently, we are holding the state in our two form elements. So let’s migrate those local states into the central state we’re keeping inside our Redux store.
Remove the constructor methods inside the LoginForm and RegistrationForm components (these were only used to initialize the states), and update our initialState object to the following:
const initialState = {
loginForm: {
token: null,
email: {
value: "",
valid: null
},
password: {
value: "",
valid: null
}
},
registrationForm: {
userId: null,
email: {
value: "",
valid: null
},
password: {
value: "",
valid: null
}
}
};
Then, we need to make this central state available to the components. We do this by passing the states down to the form components via the Route component:
<Route exact path="/register" store={store} render={() => <RegistrationForm {...store.getState().registrationForm} />} />,
<Route exact path="/login" store={store} render={() => <LoginForm {...store.getState().loginForm} />} />,
We are using store.getState() to get the current state of the store, and we are passing in only the relevant parts into the component.
Note that we are using the render prop of Route instead of the component. The render prop is useful when you want to pass in in-scope variables without causing the component to unmount and re-mount.
Then, we need to make sure that ReactDOM.render is called whenever the state changes, so the UI is a deterministic representation of our state. We do this by wrapping the ReactDOM.render call in a function, and invoking it each time the state changes by providing it as the argument to store.subscribe:
function render () {
ReactDOM.render( ... );
}
store.subscribe(render);
render();
Lastly, inside the LoginForm and RegistrationForm components, change every instance of this.state to this.props.
The UI is now a deterministic representation of our state.
Save and run yarn run serve to serve this new version of our application. You’ll notice that when you type in the input box, the value of the input box doesn't change. This is because we haven’t dispatched an action that'll alter our state.
Try changing the value of initialState.loginForm.email.value and re-serve the application. You'll see that it is reflected in the form.