Nuxt Fetch Doesn't Update on First Load

Viewed 3466

I'm having the following issue and hope someone could help me on it:

Fetch is not working on the first load (nor on reloads). It only works when on the client-side (when I move between routes).

I've read that watchQuery could help but didn't understand why and how to use it.

<script>
export default {
  async fetch() {
    const userId = await this.$nuxt.context.store.state.auth.authUser.userId
    await this.$store.dispatch('case/fetchMyCases', userId.uid)
    await this.$store.dispatch('case/fetchMyPendingCases', userId.uid)
...

It doesn't work even if I import and use firebase/auth directly.

<script>
import * as firebase from 'firebase/app'
import 'firebase/auth'
export default {
  async fetch() {
    const userId = await firebase.auth().currentUser
    await this.$store.dispatch('case/fetchMyCases', userId.uid)
    await this.$store.dispatch('case/fetchMyPendingCases', userId.uid)
...

Does anyone have any tips for it? I'd really appreciate it.

Thanks!

3 Answers

After literally 3 days searching/testing, I finally found out why I was having this issue.

The problem was that I simply put async/await for fetch but didn't put async/await for the actions itself. Therefore, my getter (in computed) was getting the store state before the dispatches have been finished.

Thanks, everyone!

Warning: You don't have access of the component instance through this inside fetch because it is called before initiating the component (server-side).

async fetch({ store }) {
  await store.dispatch('case/fetchMyCases')
  await store.dispatch('case/fetchMyPendingCases')
}

If you need parameter:

async fetch({ store, params }) {
  await store.dispatch('case/fetchMyCases', params.uid)
  await store.dispatch('case/fetchMyPendingCases', params.uid)
}

I gave an example of id. The name of the parameter depends on the name of your page.

_id => params.id
_uid => params.uid
_slug => params.slug
...

Yes, You must put async/await on actions.

async automatically returns a promise

If you don't need the value, in this case, don't anything return.

export const Actions = {
  async fetchUsers() {
     // It will return automatically promise
     await this.$axios.get('API')
  }
}

// If you need returne value
// First way
export const Actions = {
  async fetchUsers() {
   // It will return promise and value
   return await this.$axios.get('API')
  }
}

// Second way
export const Actions = {
  async fetchUsers() {
   // It will return promise and value
   const response = await this.$axios.get('API')
   return response;
 }

}

Related