Skip to content

how to store enhanced user and make it globally accessible #8

Open
@nosizejosh

Description

@nosizejosh

hello @one-aalam,

I have now been able to get user profile and want to merge that and have it globally accessible, any help on how to achieve that?

<script setup>
const subscription = ref()
const { $supabase } = useNuxtApp()
const router = useRouter()

const user = ref(null)

onMounted(() => {
  user.value = $supabase.auth.user()
  if (!user.value) {
    router.replace('/signin')
  }
  // Merge with profile
  const getUserProfile = async () => {
    const sessionUser = $supabase.auth.user();

    if (sessionUser) {
      const { data: profile } = await $supabase
        .from("profiles")
        .select("*")
        .eq("id", sessionUser.id)
        .single();
      const newUser = {
        ...sessionUser,
        ...profile,
      };
      return newUser
    }
  };

  watchEffect(() => {
    getUserProfile();
  })

  subscription.value = $supabase.auth.onAuthStateChange(async (event, session) => {
     await $fetch('/api/auth', {
      method: 'POST',
      body: { event, session }
    })
    getUserProfile();
  })
})

onUnmounted(() => {
  if (subscription.value) subscription.value?.data?.unsubscribe()
})
</script>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions