NuxtN
Nuxt8mo ago
5 replies
gentlemanfinn

Hot-reload resets component state (What is best practice?)

Hi,

What is some best practice ways to handle state in a hybrid Nuxt3 app?

The issue

When i navigate to the test page I get the profile, but whenever I change something and save(hot-reloading), the profile ends up undefined. I can use null-safe access and conditions to not get errors. But I would still need manually reload the page to work with the date. Is this the intended way?

Solution?

Run fetch onMounted? Global state with useState/Pinia? Re-populate the date using the Nuxt server cache?

Code

I have a text.vue page like this
<template>
  <h4>Server profile:</h4>
  <pre>{{ profile ?? 'ingen data' }}</pre>

  <h4>Client auth user:</h4>
  <pre>{{ clientUser ?? 'ingen data' }}</pre>

  <p v-if="pending">Loading…</p>
  <p v-if="error">Fejl: {{ error }}</p>
  <!-- <p>hej</p> -->
</template>

<script setup lang="ts">
const clientUser = useSupabaseUser()

const { data: profile, pending, error } = await useFetch('/api/me', {
  headers: useRequestHeaders(['cookie']),
})
</script>

and a server/api/me/index.get.ts
import { serverSupabaseUser } from '#supabase/server'

export default defineEventHandler(async (event) => {
  const user = await serverSupabaseUser(event)
  if (!user) {
    throw createError({ statusCode: 401, statusMessage: 'Not authenticated' })
  }

  const profile = await prisma.profile.findUnique({
    where: { userId: user.id },
    include: {
      occupancies: true,
      userRoles: { select: { role: true } },
    },
  })

  if (!profile) {
    throw createError({ statusCode: 404, statusMessage: 'Profile not found' })
  }

  return profile
})


Thanks
Was this page helpful?