After writing a mern-stack without typescript, I currently writing a webshop with typescript. I have a register-page and try to send the data out of the user-entry via redux-toolkit to the backend, in which I have the crud operations, that all are working well. I tested this with postman. But typescript don't want to send this data. It tells me:
0 arguments expected but received 1.ts(2554)
I read both documentations. Usage of typescript in redux-toolkit and typescript with react. I googled the error either, but there seems to be no solution, that explains me the behaviour of typescript. That is the register page:
const Register = () => {
const dispatch = useAppDispatch();
const selector = useAppSelector((state:RootState)=>state.auth);
const navigate = useNavigate();
const [formdata, setFormdata] = useState({
vorname:"",
nachname:"",
email:"",
street:"",
number:"",
plz:"",
city:"",
username:"",
password:"",
password_confirm:"",
})
const {vorname, nachname, email, street, number, plz, city, username, password, password_confirm} = formdata;
const {user, isLoading, isError, isSuccess, message} = selector;
useEffect(()=>{
if(isError){
toast.error(message);
}
if(isSuccess || user){
navigate('/login');
}
dispatch(reset);
}, [dispatch, isError, isSuccess, navigate, user, message])
const handleChange = (e:ChangeEvent<HTMLInputElement>)=>{
setFormdata((prevState)=>({
...prevState,
[e.target.name]: e.target.value,
}))
}
const onSubmit = (e:React.FormEvent)=>{
e.preventDefault();
if(password !== password_confirm){
toast.error("Die Passwörter stimmen nicht überein");
} else{
const userData = {
vorname,
nachname,
email,
street,
number,
plz,
city,
username,
password,
}
dispatch(register(userData))//here it not wants to have an argument
}
};
That is this register in the slice, that should get the data:
export const register = createAsyncThunk('/auth/register', async (user, thunkAPI)=>{
try{
return await authService.register(user!);
}catch (error:any) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString()
return thunkAPI.rejectWithValue(message as string)
}
})
That is the http request in the authService:
const register = async (userData:object) => {
const response = await axios.post(API_URL 'register',userData);
if(response.data){
localStorage.setItem('user',JSON.stringify(response.data))
}
return response.data
}
CodePudding user response:
you need to give type for the user with out it will create void function. this should work. replace user:UserData
with your type.
type UserData = {} // your data type you want to pass
export const register = createAsyncThunk('/auth/register', async (user :UserData, thunkAPI)=>{
try{
return await authService.register(user!);
}catch (error:any) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString()
return thunkAPI.rejectWithValue(message as string)
}
})