Wait until session is initialized

This commit is contained in:
ekzyis 2023-11-07 10:15:53 +01:00
parent 57673f7b39
commit f9d12da7d3
2 changed files with 23 additions and 13 deletions

View File

@ -8,18 +8,26 @@
import { ref } from 'vue' import { ref } from 'vue'
import { useSession } from '@/stores/session' import { useSession } from '@/stores/session'
let qr = ref(null) const qr = ref(null)
let lnurl = ref(null) const lnurl = ref(null)
const login = async () => {
const s = await session.login()
qr.value = s.qr
lnurl.value = s.lnurl
}
const session = useSession() const session = useSession()
await (async () => { // wait until session is initialized
try { if (session.initialized && !session.isAuthenticated) {
if (session.isAuthenticated) return await login()
const s = await session.login() } else {
qr = s.qr // else subscribe to changes
lnurl = s.lnurl session.$subscribe(async (_, s) => {
} catch (err) { if (s.initialized && !s.isAuthenticated) {
console.error('error:', err.reason || err) await login()
} }
})() })
}
</script> </script>

View File

@ -4,6 +4,7 @@ import { computed, ref } from 'vue'
export const useSession = defineStore('session', () => { export const useSession = defineStore('session', () => {
const pubkey = ref(null) const pubkey = ref(null)
const isAuthenticated = computed(() => !!pubkey.value) const isAuthenticated = computed(() => !!pubkey.value)
const initialized = ref(false)
async function init () { async function init () {
try { try {
@ -16,6 +17,7 @@ export const useSession = defineStore('session', () => {
} catch (err) { } catch (err) {
console.error('error:', err.reason || err) console.error('error:', err.reason || err)
} }
initialized.value = true
} }
function checkSession () { function checkSession () {
@ -35,5 +37,5 @@ export const useSession = defineStore('session', () => {
return fetch(url, { credentials: 'include' }).then(r => r.json()) return fetch(url, { credentials: 'include' }).then(r => r.json())
} }
return { pubkey, isAuthenticated, init, checkSession, login } return { pubkey, isAuthenticated, initialized, init, checkSession, login }
}) })