How to type an async callback function in onAuthStateChanged?
There is an error "Promise returned in function argument where a void return was expected." from this line.
async (user: User | null) => {
const unpdatedUser = user ? await adminUser(user) : null;
callback(unpdatedUser);
};
here is the full code.
type DispatchType = Dispatch<SetStateAction<User | null>>;
export function onUserStateChange(callback: DispatchType) {
onAuthStateChanged(auth, async (user: User | null) => {
const unpdatedUser = user ? await adminUser(user) : null;
callback(unpdatedUser);
});
}
async function adminUser(user: User | null) {
return get(ref(database, 'admins')).then((snapshot) => {
if (snapshot.exists()) {
const admins = snapshot.val();
const isAdmin = admins.include(user?.uid);
return { ...user, isAdmin };
}
return user;
});
}
You've got some type confusion around the Firebase Auth User
type and your own User
type that includes an isAdmin
Boolean.
I'd go with something like this...
import { User as FirebaseUser } from "firebase/auth";
// this is your user type
interface User extends FirebaseUser {
isAdmin: boolean;
}
You should also check for a null
user
parameter before attempting to spread it into {...user, isAdmin }
.
Your adminUser
function should return type Promise<User | null>
Promise<User | null>
async function adminUser(user: FirebaseUser | null): Promise<User | null> {
// null user
if (!user) {
return user;
}
const isAdmin =
(await get(ref(database, "admins"))).val()?.include(user.uid) ?? false;
return { ...user, isAdmin };
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.