My form has two inputs:
- username (
type="text"
) - email (
type="email"
)
I also have a .json
file as a "database" to do some validation. The submit button can only be clicked if the user enters a username that doesn't exist on the .json
file. The thing is I don't know if I should pass the "...state" object on every action.type. I am getting some bugs that seem to go away when I use the "...state", but I don't understand why nor if I should always use it.
Here's my code:
const formReducer = (state, action) => {
switch (action.type) {
case "USERNAME_INPUT":
return {
...state,
usernameValue: action.payload,
};
case "API_RETURN_USERNAME":
return {
...state,
usernameValue: action.payload.match
? action.payload.username
: "",
usernameIsValid: !action.payload.match,
emailValue: action.payload.match ? action.payload.email : "",
emailIsValid: !action.payload.email,
apiReturned: true,
};
case "EMAIL_INPUT":
return {
...state,
emailValue: action.payload.value,
emailIsValid: action.payload.isValid,
formIsValid: action.payload.isValid && state.usernameIsValid,
apiReturned: false,
};
default:
return {
usernameValue: "",
emailValue: "",
usernameIsValid: false,
emailIsValid: false,
formIsValid: false,
apiReturned: false,
};
}