I am working with a basic form. The form contains a username field, email field, password field, and a repeated password field. I'm trying to solve state management by throwing the form state in a useReducer. However, I'm not getting the buttonDisabled state to properly calculate out to what it should be. The goal is for the button to be disabled on load, and then when all fields are not empty, and when the password field and the repeated password fields match, the button will enable.
SignUpReducer.js
userName: "",
email: "",
password: "",
repeatedPassword: "",
buttonDisabled: true
}
export const formReducer = (state, action) => {
console.log(state, "STATE");
console.log(state.buttonDisabled, "BUTTON DISABLED?");
switch(action.type) {
case "Handle Input Text":
return {
[action.field]: action.payload,
buttonDisabled: state.password === state.repeatedPassword,
};
default:
return state;
}
}
SignUpPage.js
import React from "react";
import { useReducer } from "react";
import { formReducer, initialState } from "./SignUpReducer";
const SignUpPage = () => {
const [state, dispatch] = useReducer(formReducer, initialState);
const handleTextChange = (e) => {
dispatch({
type: "Handle Input Text",
field: e.target.name,
payload: e.target.value,
});
}
return (
<>
<h1>Sign Up</h1>
<label htmlFor="username">Username</label>
<input type="text" name="userName" value={state.userName} onChange={handleTextChange} id="username"/>
<label htmlFor="email">E-mail</label>
<input type="text" name="email" value={state.email} onChange={handleTextChange} id="email"/>
<label htmlFor="password">Password</label>
<input name="password" value={state.password} onChange={handleTextChange} type="password" id="password"/>
<label htmlFor="repeatedPassword">Repeat Password</label>
<input name="repeatedPassword" value={state.repeatedPassword} onChange={handleTextChange} type="password" id="repeatedPassword"/>
<button className="btn-primary" disabled={state.buttonDisabled}>Sign Up</button>
</>
)
};
export default SignUpPage;