2

I have a page like this:

<template>
  <div class="row flex">
    {{posts.id}}
  </div>
</template>
<script>
  import axios from 'axios'
  export default {
    async asyncData ({ route }) {
      let { data } = await axios.get('http://localhost:8000/api/v1/feeds/' + route.params.id + '/')
      return {
        posts: data
      }
    }
  }
</script>

When I click link with hot reload (router-link), it display well. But when I reload this window, it appear in 1 seconds and disappear then.

Video: http://g.recordit.co/ht0a0K2X81.gif

Error Log: Error Log SSR

How can I fix this?

1 Answer 1

8

Add a property to your data i.e dataLoaded: false. When your ajax request has finished, set this.dataLoaded = true. On your template add v-if="dataLoaded. This will mean the template data won't render until you're ready.

You could also do v-if="posts" as another way but I generally have a consistent dataLoaded prop available to do this.

Edit: I just looked at your example again and doing something like this would work:

<template>
  <div class="row flex" v-if="posts">
    {{posts.id}}
  </div>
</template>
<script>
  import axios from 'axios'
  export default {
    data () {
        return {
            posts: null
        }
    }
    methods:{ 
        loadPosts () {
            return axios.get('http://localhost:8000/api/v1/feeds/' + this.$route.params.id + '/')
        }
    },
    created () {
        this.loadPosts().then(({data}) => {
            this.posts = data
        })
    }
  }
</script>

I've removed the async and just setting posts when the axios request returns it's promise. Then on the template, it's only showing posts is valid.

Edit

You can also use your original code and just add v-if="posts" to the div you have in your template.

Sign up to request clarification or add additional context in comments.

15 Comments

See my edit, I've changed route.params.id to this.$route.params.id within the axios request.
This work: Change in create(): this.loadPosts().then((data) into this.loadPosts().then(({data}). It works.
Ah, good. Wasn't sure of the data structure but it was here for an example :) Glad it's working.
But do you have any better solution?
Not really, you only want to show the page when the data is loaded so this is the best approach. It's better than await as well because it means there's no blocking happening. I've used this method with great success over my app.
|

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.