Last active
December 28, 2022 06:18
-
-
Save caesaneer/7ec4d746591dc0daa2dc4fd611cc3fb9 to your computer and use it in GitHub Desktop.
Firebase user store that derives from a Firebase auth store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SVELTE | |
import { derived, type Readable } from 'svelte/store'; | |
// FIREBASE | |
import { onAuthStateChanged } from 'firebase/auth'; | |
import type { Auth, User } from 'firebase/auth'; | |
// LIB | |
import { firebaseAuth } from '$lib/firebaseAuth'; | |
import { authEmitter } from '$lib/urqlClient'; | |
function newUserStore() { | |
// export const user = createUserStore(); | |
const { subscribe } = derived<Readable<Auth>, User | null>(firebaseAuth, ($auth, set) => { | |
onAuthStateChanged($auth, (user) => { | |
if (user && user.getIdToken) { | |
user | |
?.getIdToken() | |
.then((token) => { | |
authEmitter.emit('token', token); | |
}) | |
.catch((err) => { | |
console.log('GET ID TOKEN ERROR'); | |
console.log(err); | |
// todo: handle error | |
}); | |
} else { | |
console.log('NO USER'); | |
} | |
set(user); | |
}); | |
}); | |
// known can be awaited | |
const known = new Promise<void>((resolve) => { | |
// eslint-disable-next-line @typescript-eslint/no-empty-function | |
let unsub = () => {}; | |
unsub = subscribe((user) => { | |
if (user !== null) { | |
resolve(); | |
unsub(); | |
} | |
}); | |
}); | |
return { | |
subscribe, | |
known | |
}; | |
} | |
export const user = newUserStore(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment