Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

reactjs - Value of type 'PromiseConstructor' is not callable. Did you mean to include 'new'? React TypeScript

.then not working in typescript.

interface Props {
  type: string;
  user: object;
  setUserAuth: Promise<any>;
}

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (type === "signup") {
      setUserAuth(type, { username: name, email, password })
        .then(() => history.push("/home"))
        .catch((err: React.SetStateAction<string | null>) => setError(err));
    } else {
      setUserAuth(type, { email, password })
        .then(() => history.push("/home"))
        .catch((err: React.SetStateAction<string | null>) => setError(err));
    }
  };

Promise:

export const setUserAuth = (type: string, userData: any) => (dispatch: any) => {
  return new Promise((resolve, reject) => {
    apiCall("post", `/api/auth/${type}`, userData)
      .then(({ token, ...user }: any) => {
        localStorage.setItem("jwtToken", token);
        setAuthorizationToken(localStorage.jwtToken);
        dispatch({
          type: SET_USER,
          payload: {
            user,
          },
        });
        resolve(user);
      })
      .catch((err: any) => reject(err));
  });
};

Error:

/home/vivek/Documents/Projects/Showcase Projects/fullstack-frontend/src/components/auth.tsx
TypeScript error in /home/vivek/Documents/Projects/Showcase Projects/fullstack-frontend/src/components/auth.tsx(23,20):
Value of type 'PromiseConstructor' is not callable. Did you mean to include 'new'?  TS2348

    21 |     e.preventDefault();
    22 |     if (type === "signup") {
  > 23 |       setUserAuth(type, { username: name, email, password })
       |                    ^
    24 |         .then(() => history.push("/home"))
    25 |         .catch((err: React.SetStateAction<string | null>) => setError(err));
    26 |     } else {

How can it be resolved...?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

setUserAuth is not a Promise. it's a function returning a promise.

it should be typed like this:

setUserAuth: (type: SomeType, options: UserOptions) => Promise<any>

(replace the argument types with the real types from your code)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...