0

I'm currently developing a universal app using Nuxt.js, the data on most of the pages is retrieved from an API using a fetch hook as well as vuex store. I started noticing errors on page reload/refresh and sometimes when I visit a page from the navbar. The page error is:

TypeError: Cannot read property 'data' of undefined

where data is an object retrieved from an API. I have searched around the internet for this and found it has something to do with data not being loaded or page rendering whilst the data is not fully retrieved. i have found a work around by using a v-if on my template to check if the data is set then display the contents. my question is if there is a way to achieve this, i have tried using the async/await keywords but it doesn't help and i feel like the v-if method is not the best way to handle it.

edit: solved by using $fetchState.pending when using fetch()

2
  • could you show us the error please? in the console you see usually where the error appears Commented Aug 19, 2020 at 7:26
  • I have managed to solved the error with the $fetchState.pending thank you for your time Commented Aug 20, 2020 at 5:50

1 Answer 1

5

If in your template you display right away the data you retrieve from the API, then indeed using the v-if is the right way to do.

If you are using the new fetch() hook, then in your template you can use $fetchState.pending to check if the loading has finished, for example:

<div v-if="$fetchState.pending"> 
 <p> Content is loading... </p>
</div>

<div v-else>
 <p> Content has loaded! {{data}}</p>
</div>

<script>
 export default{
  data(){
   return{
    data: null
   }
  }

  async fetch(){
   this.data = await getSomeAPI
  }
 }
</script>
   
Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome, if you mark this as the right answer would be appreciated, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.