I am using firebase auth with TS in a nextJS app.
I am trying to setup AuthProvider and use context.
interface IAuth {
user: User | null;
login: (data: FormData) => Promise<firebase.auth.UserCredential>;
logout: () => void;
}
type FormData = {
email: string;
password: string;
};
type User = firebase.User;
// type UserCredential=firebase.auth.UserCredential
const AuthContext = createContext<IAuth>({
user: null,
login:(data: FormData) => Promise<firebase.auth.UserCredential>,
logout: () => {},
});
I am getting this warning on login
function that says:
Type '(data: FormData) => boolean' is not assignable to type '(data: FormData) => Promise<UserCredential>'.
Type 'boolean' is not assignable to type 'Promise<UserCredential>'.
Here is my auth.tsx
export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => {
firebaseClient();
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
return firebase.auth().onIdTokenChanged(async (user) => {
console.log('auth changed');
console.log(user ? user.getIdToken : 'Nothing');
if (!user) {
setUser(null);
nookies.set(undefined, 'token', '', {});
return;
}
const token = await user.getIdToken();
setUser(user);
nookies.set(undefined, 'token', token, {});
});
}, []);
const login = async (data: FormData): Promise<firebase.auth.UserCredential> => {
return await firebase.auth().signInWithEmailAndPassword(data.email, data.password);
};
const logout = async () => {
console.log('Logging out');
return await firebase.auth().signOut()
};
return <AuthContext.Provider value={{ user, login, logout }}>{children}</AuthContext.Provider>;
};
export const useAuth = () => useContext(AuthContext);
How do I mention the return type in AuthContext?
const AuthContext = createContext<IAuth>({
user: null,
login:(data: FormData) => Promise<firebase.auth.UserCredential>,
logout: () => {},
});
CodePudding user response:
You need to return a Promise<firebase.auth.UserCredential>
from login method but you just have the type written atm. Try refactoring the code to:
const login = async (data: FormData) => {
return await firebase.auth().signInWithEmailAndPassword(data.email, data.password);
};
const AuthContext = createContext<IAuth>({
user: null,
login:(data: FormData) => login, // <-- add the function here
logout: () => {},
});