Search code examples
vue.jscomputed-properties

How to avoid 404 error for a computed property which relies on a variable obtained from API call?


I want to display an image whose source is a computed property which relies on an API call. It works but I get a 404 error message in console which I'd like to not see.

Here's my image:

<img :src="userPhotoUrl" />

And here's the computed property and the stuff it depends on:

computed: {
  ...mapState({
    user: state => state.dashboard.user || {},
    storageBaseUrl: state => state.storageBaseUrl || ''
  }),
  userPhotoUrl() {
    try {
      return `${this.storageBaseUrl}${this.user.photo}`
    } catch (error) {
      return ""
    }
  }

Any idea how to avoid the 404?


Solution

  • Given the fact that your image makes no sense if there is not a valid url, I would not include it if there is not a valid url

    <img v-if="baseurl" :src="url" />
    

    const store = new Vuex.Store({
      state: {baseurl:false}
    })
    Vue.use(Vuex)
    
    var vm = new Vue({
      el:'#app',
      store,
      computed: {
        baseurl () { return this.$store.state.baseurl},
        url () { return this.baseurl + '/hn-images/1*Pki08Q31XRtQA8zLl2Gn1w.png'}
      },
      template: '<p><img :src="url" v-if="baseurl"/></p>'
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.2/vuex.min.js"></script>
    <button onclick="vm.$store.state.baseurl='https://hackernoon.com'">load baseurl</button>
    <div id="app"></div>