typescript 异步/等待返回contextApi中未定义的内容

zi8p0yeb  于 2023-01-10  发布在  TypeScript
关注(0)|答案(2)|浏览(127)

我正在使用Context创建一个登录结构,但在AuthProvider中,异步函数仍然返回undefined。我正在尝试教授登录,axios返回API的响应,但在AuthProvider中,常量数据仍然未定义。如果您能帮助我,我将非常感激。无论如何,谢谢。我的AuthProvider:

import { useState } from "react";
import { useApi } from "../../hooks/useApi";
import { User } from "../../types/User";
import { AuthContext } from "./AuthContext";

export const AuthProvider = ({ children }: { children: JSX.Element }) => {
  const [user, setUser] = useState<User | null>(null);
  const api = useApi();

  const login = async (email: string, password: string, userType: string) => {
    const data = await api.login(email, password, userType);
    console.log(data);

    if (userType === "professor") {
      console.log("data");
      if (data?.admin && data.token) {
        setUser({
          name: data?.admin.name,
          email: data?.admin.email,
          id: data?.admin.id,
          userType: userType,
        });
        return true;
      }
    } else if (userType === "student") {
      if (data?.student && data.token) {
        setUser({
          name: data.student.name,
          email: data.student.email,
          id: data.student.id,
          userType: userType,
        });
      }
      return true;
    }

    return false;
  };

  const logout = () => {
    setUser(null);
  };

  return (
    <AuthContext.Provider value={{ user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

我的用途Api:

import axios from "axios";

const api = axios.create({
  baseURL: process.env.REACT_APP_BASE_URL,
});

export const useApi = () => ({
  login: async (email: string, password: string, userType: string) => {
    if (userType === "professor") {
      const options = {
        method: "POST",
        url: process.env.REACT_APP_BASE_URL + "/adm/admin/login",
        headers: { "content-type": "application/json" },
        data: {
          email: email,
          password: password,
        },
      };

      axios
        .request(options)
        .then((response) => {
          console.log(response.data);
          return response.data;
        })
        .catch(function (error) {
          console.error(error);
        });
    } else if (userType === "student") {
      const response = await api.post("/aluno/student/login", {
        email,
        password,
      });
      return response.data;
    }
  },
});
ykejflvf

ykejflvf1#

对于professor login部分代码--axios请求没有被等待,axios调用本身也没有作为承诺返回,所以数据基本上丢失了,所以,只需添加一个return

return axios
  .request(options)
  .then((response) => {
    console.log(response.data);
    return response.data;
  })
  .catch(function (error) {
    console.error(error);
  });

或者

const responseData = await axios
  .request(options)
  .then((response) => {
    console.log(response.data);
    return response.data;
  })
  .catch(function (error) {
    console.error(error);
  });
return responseData;

注:其他问题是由于<form> html标签本身,onClick附加到表单内的按钮,因此当点击时-页面只是重新加载。
相关:<form onSubmit={e => e.preventDefault()}>

csga3l58

csga3l582#

我认为您只是在axios.request()调用前面缺少了一个returnif (userType === "professor")分支没有返回任何aka undefined
then() arrow函数中,您将返回数据,但api.login()函数不会再次返回此数据。

相关问题