I’m using useReducer
for my Login/Register form.
When I’m using logging the reducer value, it just returns the default value, whereas it works perfectly find when logging it on useEffect hook.
Here’s a short part of my code:
//reducer
function reducer(state: State, action: Action): State {
switch (action.type) {
case "SET_EMAIL":
return { ...state, email: action.payload };
case "SET_NAME":
return { ...state, name: action.payload };
default:
return state;
}
}
// load reducer
const [state, dispatch] = useReducer(reducer, { email: "" });
//elements:
const registerElements: Elements[] = [
{
type: "text",
name: "name",
placeholder: "name",
onChange: (e) => dispatch({ type: "SET_NAME", payload: e.target.value }),
value: state.name || "",
},
{
type: "email",
name: "email",
placeholder: "email",
onChange: (e) => dispatch({ type: "SET_EMAIL", payload: e.target.value }),
value: state.email || "",
},
];
//input
{(action === "signin" ? loginElements : registerElements).map(
(loginElement) => (
<input
required
key={loginElement.name}
type={loginElement.type}
name={loginElement.name}
placeholder={loginElement.placeholder}
onChange={loginElement.onChange}
value={loginElement.value}
className="w-full border-b-2 border-white bg-transparent px-0 py-1 capitalize text-white transition placeholder:text-gray-200 focus-visible:border-b-yellow focus-visible:outline-none"
/>
),
)}
When I console.log
it on submit
, it remains the default value.
However, when I use useEffect
like this:
useEffect(() => {
console.log(state);
}, [state]);
It is logging the value as in the input
What can I do to fix this issue?