Issue with onAuthStateChange in Pinia + Supabase

I have a Pinia store with updateSettings function to update user settings in Supabase.

I use supabase.auth.onAuthStateChange to initialize the store (currentTopics, currentLevel, etc.) when a user signs in.

On page reload, onAuthStateChange fires immediately with the existing session, and I see console.log('Updated') to appear even though the user hasn’t actually signed in again (the token already exists).

If I try to call another async function updateSettings after that, it sometimes fails because supabase.auth.getUser() in there may return null or undefined temporarily, depending on how the session is restored.
supabase.auth.onAuthStateChange((event, session) => {
    setTimeout(async () => {
        if (event === 'SIGNED_IN') {
            const { data, error } = await supabase
                .from('study_settings')
                .select<'*', StudySettings>('*')
                .eq('user_id', session.user.id)
                .single();

            if (error) return;

            if (data) {
                currentLevel.value = levels.value.indexOf(data.level);
            }
            console.log('Updated', levels.value[currentLevel.value]);
        }
    }, 0);
});

Any solution? Where should I keep onAuthStateChange?
Was this page helpful?