Home > Net >  vuex store variable is used before it is filled in store with data from API
vuex store variable is used before it is filled in store with data from API

Time:04-19

I am trying to get data from API through vuex.

This is an action function in store:

async getEpisodeFromApi({ commit }, id) {
      const data = {
        id
      };

      return await axios.get(Api.getUrl(data)).then((response) => {
        console.log("response.dat0dfgsdfa", response.data);
        commit("setEpisode", response.data);
      });
    }

This is an Api class (it returns the link string):

class Api {
  getUrl(data) {
    return "https://www.breakingbadapi.com/api/episodes/"   data.id;
  }
}

export default new Api();

And this is how I tried to interact with data.

 async beforeCreate() {
    await this.$store.dispatch(
      "getEpisodeFromApi",
      this.$route.params.episode_id
    );
  },
  async mounted() {
    const episode = this.$store.state.episode;
    episode.characters.forEach((name) => {
      this.charactersInEpisode.push(
        this.$store.characters.find((character) => character.name === name)[0]
      );
    });
}

But store fills state slowlier than mounted hooks begin to work. And I always get episode as an empty variable and episode.characters is undefined.

episode.characters is undefined

How can I fill state in store and get the data from store faster than mounted hook runs code?

CodePudding user response:

You ca try to convert beforeCreated hook to method

methods: {
  async getData() {
    await this.$store.dispatch(
      "getEpisodeFromApi",
      this.$route.params.episode_id
    );
  },
}

then in mounted hook await for data:

async mounted() {
  await this.getData()
  const episode = this.$store.state.episode;
  episode.characters.forEach((name) => {
    this.charactersInEpisode.push(
      this.$store.characters.find((character) => character.name === name)[0]
    );
  });
}

CodePudding user response:

This may be a computed property. It will be updated when the state fills with data from API:

computed: {
    charactersInEpisode(){
        const episode = this.$store.state.episode;
        if (!episode) return []
        return episode.characters.map((name) => {
           return this.$store.state.characters.find((character) => character.name === name)[0]
        });
    }
}
  • Related