@aleshaykovlev
html, css, js, node, webpack, sass, react

Ошибка при отправке данных в redux?

Ошибка:
Argument of type 'object' is not assignable to parameter of type 'IUser'.
  Type '{}' is missing the following properties from type 'IUser': name, email, avatar, cart


Функция для отправки данных:
export const login = (userLog: IUser, setMessage: React.Dispatch<React.SetStateAction<IMessage>>) => {
    return async (dispatch: React.Dispatch<IUser>) => {
        try {
            const response: any = await fetch("/api/auth/login", {
                method: "POST",
                body: JSON.stringify(userLog),
                headers: {
                    "Content-Type": "application/json"
                }
            });

            dispatch(setUserAction(response.data.dataUser)); // ошибка здесь
            localStorage.setItem("token", response.data.token);
        } catch(e) {
            setMessage({
                text: "Ошибка сервера, попробуйте позже",
                type: "error"
            })
        }
    }
}


Redux Action:
import { IUser } from "../../types";

export const setUserAction = (user: IUser): object => {
    return {
        type: "SET_USER_ACTION",
        payload: user
    }
}


interface user:
export interface IUser {
    name: string,
    email: string,
    password?: string,
    avatar: string,
    cart: Array<Object>,
    roles?: []
}


reducer user:
import {IUser} from "../../types";

const SET_USER = "SET_USER";
const SET_USER_CART_ACTION = "SET_USER_CART_ACTION";

interface IInitianUser {
    infoUser: IUser, cart: Array<Object>, isAuth: boolean
}

const initialUser: IInitianUser = {
    infoUser: {
        name: "",
        email: "",
        avatar: "",
        cart: [],
        roles: []
    }, cart: [], isAuth: false
}

interface IAction {
    type: string,
    payload: IUser
}

export default function user(state = initialUser, action: IAction) {
    switch(action.type) {
        case SET_USER:
            return {
                ...state,
                infoUser: action.payload,
                isAuth: true
            }
        case SET_USER_CART_ACTION:
            return {
                ...state,
                cart: action.payload
            }
        default:
            return state;
    }
}
  • Вопрос задан
  • 70 просмотров
Решения вопроса 1
@aleshaykovlev Автор вопроса
html, css, js, node, webpack, sass, react
From: dispatch: React.Dispatch<IUser>
export const login = (userLog: IUser, setMessage: React.Dispatch<React.SetStateAction<IMessage>>) => {
    return async (dispatch: React.Dispatch<IUser>) => {
        try {
            const response: any = await fetch("/api/auth/login", {
                method: "POST",
                body: JSON.stringify(userLog),
                headers: {
                    "Content-Type": "application/json"
                }
            });

            response.json().then((data: any) => {
                dispatch(setUserAction(data.dataUser));
                localStorage.setItem("token", data.token);
            });
        } catch(e: any) {
            setMessage({
                text: "Ошибка сервера, попробуйте позже " + e.message,
                type: "error"
            })
        }
    }
}


To: dispatch: React.Dispatch<object>
export const login = (userLog: IUser, setMessage: React.Dispatch<React.SetStateAction<IMessage>>) => {
    return async (dispatch: React.Dispatch<object>) => {
        try {
            const response: any = await fetch("/api/auth/login", {
                method: "POST",
                body: JSON.stringify(userLog),
                headers: {
                    "Content-Type": "application/json"
                }
            });

            response.json().then((data: any) => {
                dispatch(setUserAction(data.dataUser));
                localStorage.setItem("token", data.token);
            });
        } catch(e: any) {
            setMessage({
                text: "Ошибка сервера, попробуйте позже " + e.message,
                type: "error"
            })
        }
    }
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы