Reputation: 89
I'm just trying useReducer on react. What ever I type, the values are geting printed double and also twice, as shown in below image.
I don't understand why. Below is my code .
import { useReducer } from "react";
import "./sign.scss";
const SignIn = () => {
const handleCredentials = (state: SignInCredentialsInit, action: { type: string, payload: string }) => {
if (action.type === 'EMAIL') {
console.log(action.payload);
return {
...state,
email: state.email + action.payload
}
}
if (action.type === 'PASSWORD') {
return {
...state,
password: state.password + action.payload
}
}
}
const [credentials, updateCredential] = useReducer(handleCredentials, {
email: "", password: ""
});
return (
<section>
<div className="signInBox">
<p className="signInText">SIGN IN</p>
<form>
<div className="inputFlex">
<input
className="inputBox"
type="email" required
value={credentials.email}
onChange={e => updateCredential({ type: 'EMAIL', payload: e.target.value })}
/>
<input className="inputBox" type="password" required />
<button ></button>
</div>
</form>
</div>
</section>
)
}
export default SignIn;
Also getting a warning on useReducer as:
No overload matches this call. Overload 1 of 5, '(reducer: ReducerWithoutAction, initializerArg: any, initializer?: undefined): [any, DispatchWithoutAction]', gave the following error. Argument of type '(state: SignInCredentialsInit, action: { type: string; payload: string;}) => { email: string; password: string | null; } | { password: string; email: string | null; } | undefined' is not assignable to parameter of type 'ReducerWithoutAction'. Target signature provides too few arguments. Expected 2 or more, but got 1. Overload 2 of 5, '(reducer: (state: SignInCredentialsInit, action: { type: string; payload: string; }) => { email: string; password: string | null; } | { password: string; email: string | null; } | undefined, initialState: never, initializer?: undefined): [...]', gave the following error. Argument of type '{ email: string; password: string; }' is not assignable to parameter of type 'never'.t
Can someone help me with this?
Upvotes: 0
Views: 193
Reputation: 1
First of all, it would be better to move this "reducer Handler" to a separate file. And you should remove the add operation to the previous value from your expression. But I generally recommend you not to use Reducer for these purposes.
If we are talking specifically about double output to the console - then you should read the documentation. https://react.dev/reference/react/StrictMode
if (action.type === 'EMAIL') {
console.log(action.payload);
return {
...state,
email: action.payload // deleted: **state.email**
}
}
if (action.type === 'PASSWORD') {
return {
...state,
password: action.payload // deleted: **state.password**
}
}
Upvotes: 0