Home > OS >  When I am trying to import a custom hook function I am getting a typescript error
When I am trying to import a custom hook function I am getting a typescript error

Time:02-12

I am trying to import my custom hook function(RegisterUser) on my register page. but when I am trying to import like this const { RegisterUser } = UseFirebase() I am getting an error which is const RegisterUser: any Property 'RegisterUser' does not exist on type 'readonly [(email: string, password: string, name: string, history: any) => Promise<void>]'.

This is my custom hook function.

export default function UseFirebase() {
    const [user, setUser] = useState({})
    const [error, setError] = useState('')
    const [admin, setAdmin] = useState(false)
    const [isLoading, setIsLoading] = useState(true)
    const auth = getAuth()


    // REGISTER WITH EMAIL AND PASSWORD
    const RegisterUser = async (email: string, password: string, name: string, history: any) => {
        setIsLoading(true)
        const userCredential = await createUserWithEmailAndPassword(auth, email, password)

        const newUser = {
            email,
            displayName: name
        };

        setUser(newUser);
        setError('')

        // Pass userCredential.user instead of auth.currentUser
        updateProfile(userCredential.user, {
            displayName: name
        }).then(() => { }).catch((error) => { });
        history.replace('/');
    }

    return [RegisterUser] as const

}

Can anyone help me, please? How can I solve the error?

CodePudding user response:

I'm not sure what you are trying to do but you typed your component as React.FunctionComponent<IUseFirebaseProps> but you returning [RegisterUser] as const and RegisterUser is not the correct return type for React.FunctionComponent<IUseFirebaseProps> or React.ReactElement<any, any> | null.

If you are trying to make a custom hook, you should remove React.FunctionComponent<IUseFirebaseProps> and React.ReactElement<any, any> | null which aren't necessary in a custom hook.

Also, a custom hook don't need to receive props of the type React.PropsWithChildren<IUseFirebaseProps>, maybe just use IUseFirebaseProps as a normal function parameter.

I'm guessing here, but you probably need something like this:

// type for the RegisterUserFunction
type RegisterUserFunction = (
  email: string,
  password: string,
  name: string,
  history: any
) => Promise<void>;

const UseFirebase = (
  props: IUseFirebaseProps, // it's not the props from a component, but more like a normal function parameter
  context?: any
): [RegisterUserFunction] => {
  // other hooks

  // REGISTER WITH EMAIL AND PASSWORD
  const RegisterUser: RegisterUserFunction = async (
    email: string,
    password: string,
    name: string,
    history: any
  ) => {
    // your function
  };

  return [RegisterUser]; // no need to use as const
};
  • Related