Search code examples
javascriptvue.jses6-promisevuejs3vuex4

Fetching a data object with Vuex action and get "Uncaught (in promise) TypeError" when i try to take data into these object


I am learning Vuex, and most recently its actions which I use to fetch data.

Everything seems to work, I can access my films object, I can select any film in this object ... But once I want to access a data contained in one of these films, an error message wakes up my console.

Vuex:

export default createStore({
  state: {
    films: []
  },

  mutations: {
    SET_FILMS(state, films) {
      state.films = films
    }
  },

  actions: {
    fetchFilms({ state, commit }){
        services_movieDB.getFilms('')
        .then(response => {
          commit('SET_FILMS', response.data.results)
        })
        .catch(error => console.log("error with api call getFilms() in CardFilms", error))
      }

    }
});

*services_movieDB is a service for fetching datas with Axios.To keep this question clear, I'll spare you this part: it works.

Component:

<template>
  <section>
    {{ films[currentIndex] }} //it works: no error message
    {{ films[currentIndex] }} //it works: but 2 warnings and 1 error message in the console
    {{ currentFilm }} //isn't work
  </section>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "CardFilms",
  data() {
    return {
      currentIndex: 0,
      currentFilm: null
    };
  },
  computed: {
    ...mapState(["films"]),
  },
  beforeCreate(){
    this.$store.dispatch("fetchFilms")
    this.currentFilm = this.$store.state.films[this.currentIndex]
  },
};
</script>

Warnings:

[Vue warn]: Unhandled error during execution of render function 
  at <CardFilms> 
  at <Acceuil onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <RouterView> 
  at <App> 
[Vue warn]: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next 
  at <CardFilms> 
  at <Acceuil onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <RouterView> 
  at <App>

Error:

Uncaught (in promise) TypeError: can't access property "title", _ctx.films[$data.currentIndex] is undefined

This is really a Vue internals bug? Some body have a solution? VueJS 3 | Vuex 4


Solution

  • Add conditional rendering (v-if), so you do not render without data.

     <section v-if="currentFilm && films">