vuejs3piniavue-suspense

Vue3 await for Pinia data


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.


Solution

  • 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>