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

View File

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