I am getting the error on my useReducer function.
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: any, action: any) => { value: any; isValid: boolean; }' is not assignable to parameter of type 'ReducerWithoutAction'. Overload 2 of 5, '(reducer: (state: any, action: any) => { value: any; isValid: boolean; }, initialState: { value: any; isValid: boolean; }, initializer?: undefined): [{ value: any; isValid: boolean; }, Dispatch]', gave the following error. Type 'null' is not assignable to type 'boolean'.ts(2769) Search.tsx(15, 35): The expected type comes from property 'isValid' which is declared here on type '{ value: any; isValid: boolean; }'
This is my code. Strangely if I change the return statement for the reducer
return { value: action.value, isValid: action.value.length === 13 };
to
return { value: action.value, isValid: action.value.includes('@')};
Then it the errors go away.
import React, { useState, useEffect, useReducer } from "react";
import Card from "../UI/Card/Card";
import classes from "./Login.module.css";
import Button from "../UI/Button/Button";
interface searchInputState {
value: string,
isValid: boolean | null
}
const mprnInputReducer = (state: any, action: any) => {
console.log("emailReducer runs");
if (action.type === "MPRN_INPUT") {
return { value: action.value, isValid: action.value.length === 13};
}
if (action.type === "MPRN_BLUR") {
return { value: state.value, isValid: state.value.length === 13 };
}
return { value: "", isValid: false };
};
const Search = (props: any) => {
const [formIsValid, setFormIsValid] = useState(false);
const [mprnInputState, dispatchMPRN] = useReducer(mprnInputReducer, {
value: "",
isValid: null,
});
const mprnChangeHandler = (event: any) => {
console.log("emailChangeHandler runs");
dispatchMPRN({ type: "MPRN_INPUT", val: event.target.value });
setFormIsValid(event.target.value.trim().length == 13);
};
const validateMPRNHandler = () => {
console.log("validatePasswordHandler runs");
dispatchMPRN({ type: "MPRN_BLUR" });
};
const submitHandler = (event: any) => {
console.log("submitHandler runs");
event.preventDefault();
props.onSearch(mprnInputState.value);
};
return (
<Card className={classes.login}>
<form onSubmit={submitHandler}>
<div
className={`${classes.control} ${
mprnInputState.isValid === false ? classes.invalid : ""
}`}
>
<label htmlFor="search">E-Mail</label>
<input
type="searchInput"
id="searchInput"
value={mprnInputState.value}
onChange={mprnChangeHandler}
onBlur={validateMPRNHandler}
/>
</div>
<div className={classes.actions}>
<Button type="submit" className={classes.btn} disabled={!formIsValid}>
Login
</Button>
</div>
</form>
</Card>
);
};
export default Search;
Could someone help me resolve this?