У меня есть функция, которая принимает юзернейм и пароль, и должна менять данные в стейте, однако она почему-то их не меняет,почему?
Редьюсер
import {createSlice, PayloadAction} from "@reduxjs/toolkit"
import { IUser } from "../../models/models"
interface IAuthState {
isAuth: boolean,
user: IUser,
isAuthLoading: boolean,
authError: string | null
}
const initialState: IAuthState = {
isAuth: false,
user: {} as IUser,
isAuthLoading: false,
authError: null,
}
export const authSlice = createSlice({
name : "auth",
initialState,
reducers: {
setIsAuthLoading : (state: IAuthState,action:PayloadAction<boolean>) => {
state.isAuthLoading = action.payload;
},
setAuthError: (state:IAuthState,action:PayloadAction<string>) => {
state.authError = action.payload;
},
setAuth: (state:IAuthState, action:PayloadAction<boolean>) => {
state.isAuth = action.payload;
},
setUser: (state:IAuthState, action:PayloadAction<IUser>) => {
state.user = action.payload;
}
},
})
export default authSlice.reducer;
export const {setAuth,setAuthError,setIsAuthLoading,setUser} = authSlice.actions;
Функция
import { IUser } from "../../models/models";
import { AppDispatch } from "../store";
import axios from "axios";
import { setAuth, setAuthError, setIsAuthLoading, setUser } from "./AuthSlice";
export const login = (username:string,password: string) => async (dispatch: AppDispatch) => {
try{
dispatch(setIsAuthLoading(true));
const response = await axios.get<IUser[]>('./users.json');
const user = response.data.find(user => user.username === username && user.password === password);
dispatch(setIsAuthLoading(false));
dispatch(setAuth(true));
if(user) {
dispatch(setUser(user));
}
else{
dispatch(setAuthError("Пользователь не найден"));
}
console.log(user);
}
catch (e) {
dispatch(setAuthError("Ошибка при логине"));
console.log(e)
}
}
Компонент
import React, {useState,useEffect} from "react";
import { useAppDispatch } from "../../hooks/hooks";
import { login } from "../../store/reducers/ActionCreators";
export const Login = () => {
const [username,setUsername] = useState("");
const [password,setPassword] = useState("");
const dispatch = useAppDispatch()
useEffect(() => {
console.log(username,password)
},[username,password])
const handleUsername = (e:any) => {
setUsername(e.target.value)
}
const handlePassword = (e:any) => {
setPassword(e.target.value)
}
const handleLogin = () => {
dispatch(login(username,password));
}
return (
<div>
<input value={username} onChange={handleUsername} type="text"/>
<input value={password} onChange={handlePassword} type="password"/>
<button onClick={handleLogin}>Login</button>
</div>
)
}