1

I'm trying to use Suspense to show a loading spinner. It works fine when using with fetch directly. However in some cases it doesn't work since I need to await for data already being fetched from another component.

Navbar --> userStore.fetchUser()
Main --> await userStore.user

App.vue:

<template>
  <header>
    <!-- this fetches user -->
    <Nav />
  </header>

  <div>
    <Suspense>
      <!-- I need to await inside this component -->
      <RouterView />
      <template #fallback>
        LOADING...
      </template>
    </Suspense>
  </div>
</template>

I assume this doesn't work since the Suspense is bit wrapping the Nav. But how can I achieve this since I want the nav to always be visible? And the data needs to be fetched inside Nav to show the user's name.

Pithikos
  • 18,827
  • 15
  • 113
  • 136

1 Answers1

2

You can do this the old school way without Suspense. Just set a variable userInitated: false in your store, which you set to true after the user is successfully fetched in the userStore.fetchUser function.

In your template you can set something like:

<div>
   <template v-if="userStore.userInitiated">
      <RouterView/>
   </template>
   <template v-else>
      LOADING... 
   </template>
</div>
Gabe
  • 2,168
  • 2
  • 4
  • 16
  • Thanks. That's what I ended up doing in the end. Seems all the bells & whistles added in Vue3 just overcomplicate everything. – Pithikos May 27 '23 at 11:46
  • I agree. Suspense seems just too fragile, while I think this solution is quite elegant since the working and purpose are immediately clear. – Gabe May 27 '23 at 12:02