Home > Back-end >  Promise<UserCredential> is not assignable to type
Promise<UserCredential> is not assignable to type

Time:06-02

import React, {createContext, useContext, useEffect, useState, ReactNode} from "react";
import { auth } from '../utils/init-firebase';
import { createUserWithEmailAndPassword } from "firebase/auth"

type ButtonProps = {
    children: ReactNode;
    
}

export const useAuth = () =>useContext(AuthContext);

const AuthContext = createContext({
    currentUser: null,
    register: Promise,
})

export default function AuthContextProvider( { children}  : ButtonProps){
    const [currentUser, setCurrentUser] = useState(null);

    function register(email: string, password:string) {
        return createUserWithEmailAndPassword(auth, email, password)
    }
    
    const value = {
        currentUser,
        register,
    }
    
    return <AuthContext.Provider value={value}>
        {children}
    </AuthContext.Provider>
}

I encounter error like this:

Type '{ currentUser: null; register: (email: string, password: string) => Promise<UserCredential>; }' is not assignable to type '{ currentUser: null; register: PromiseConstructor; }'.
  Types of property 'register' are incompatible.
    Type '(email: string, password: string) => Promise<UserCredential>' is missing the following properties from type 'PromiseConstructor': all, race, reject, resolve, and 3 more.

How do I solve this problem?

CodePudding user response:

Change

const AuthContext = createContext({
    currentUser: null,
    register: Promise,
})

to

const AuthContext = createContext({
    currentUser: null,
    register: (email: string, password: string) => Promise.resolve(),
})

The problem is that you're initialising register with Promise class.

It's good practice to type your context as well. To do that change:

const AuthContext = createContext({
    currentUser: null,
    register: Promise,
})

to:

type AuthContextType = {
  currentUser: User | null; //I'm not sure what can be stored in User value, currently you have there only `null`
  //it's unclear what return type `createUserWithEmailAndPassword` function has. I gues it's something like UserCredential, basing on documentation: https://firebase.google.com/docs/reference/js/v8/firebase.auth.Auth#createuserwithemailandpassword  
  register: (email: string, password: string) => Promise<UserCredential | void>
}
const AuthContext = createContext<AuthContextType>({
    currentUser: null,
    register: (email: string, password: string) => Promise.resolve(),
})
  • Related