Hariharan
Hariharan

Reputation: 49

Typescript error in a Context for Firebase Auth: Argument of type 'User' is not assignable to parameter of type 'SetStateAction<User | null>'

I'm creating an AuthContext for my react app through firebase auth. I already tried the solution in Argument of type 'User | null' is not assignable to parameter of type 'SetStateAction<User | null>'. But it is throwing me the same error as follows:

Error on setCurrentUser(firebaseUser);

Argument of type 'User' is not assignable to parameter of type 'SetStateAction<User | null>'. Type 'User' is missing the following properties from type 'User': linkAndRetrieveDataWithCredential, linkWithCredential, linkWithPhoneNumber, linkWithPopup, and 14 more.ts(2345)

Whole code:

import { auth } from '../utils/firebase'
import { createUserWithEmailAndPassword, onAuthStateChanged } from 'firebase/auth'
import firebase from "firebase/compat/app"

// type firebaseUserType = firebase.User | null

const AuthContext = React.createContext<firebase.User | null>(null);

export function useAuth() {
  return useContext(AuthContext)
}

export function AuthProvider({ children }: { children: React.ReactNode }) {

  const [currentUser, setCurrentUser] = useState<firebase.User | null>(null)


  function signup(email: string, password: string) {
    return createUserWithEmailAndPassword(auth, email, password)
  }

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, firebaseUser => {
      if(firebaseUser){
        setCurrentUser(firebaseUser);
      }
    });

    return () => { 
      unsubscribe();
    }

  }, [])

  const value = {
    currentUser,
    signup
  }

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}

It would be great if someone can point out where I am going wrong!

Upvotes: 0

Views: 560

Answers (1)

Vlad Vladov
Vlad Vladov

Reputation: 398

Try using firebase.UserInfo in Context and useState instead of firebase.User Plus the return will be

return (
    <AuthContext.Provider value={currentUser}>
        {children}
    </AuthContext.Provider>
)

Upvotes: 1

Related Questions