nuxt-starter-kit
nuxt-starter-kit copied to clipboard
how to store enhanced user and make it globally accessible
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>
Hey @nosizejosh Thanks for your interest in the starter kit, and I'm glad you were able to get the user profile. The best way I think you'd be able to do it is by creating a global store with something like Pinia(refer SSR guide) or just use good `ol context Provide/Inject pattern. There's a great discussion going here on global store pattern.
I'll try to give the global store pattern some thought, and will add an example once the time allows.