NuxtN
Nuxt2w ago
4 replies
Dante

useState or Ref

I was wondering, in a composable like this, which is better, useState or ref

export const useUser = () => {
  // Shared, SSR-safe state
  const user = useState<any | null>('user', () => null)
  const loading = useState<boolean>('user-loading', () => false)
  const error = useState<string | null>('user-error', () => null)

  const fetchUser = async () => {
    loading.value = true
    error.value = null

    try {
      const { data } = await useFetch('/api/user', {
        credentials: 'include', // important for auth cookies
      })

      user.value = data.value
    } catch (err) {
      error.value = 'Failed to fetch user'
      user.value = null
    } finally {
      loading.value = false
    }
  }

  const clearUser = () => {
    user.value = null
  }

  return {
    user,
    loading,
    error,
    fetchUser,
    clearUser,
  }
}
Was this page helpful?