Search code examples
vue.jsfetchvuextwitchtwitch-api

Fetch only once data from twitch API


I need to do 3 request to the twitch API (grap the info about the live, about the streamer and the game). I can't to it one shot because the data from the live is not already available for fetch the other data. How can I do it without the need of refresh the server (and re-fetch) 2 times?

I want to recreate the twitch thumbnail (img, name of the game, ...) For fetch for the streamer and the game, I need first the data from the live. When I charge my site, the data from the stream is fetch successfully, but the data from the streamer and the game is null.

I tried to fetch first the live data in created() and than the streamer and the game data in mounted() but i need 2 or 3 refresh for all the data is fetch successfully

<script>
import { mapActions, mapGetters } from "vuex";
export default {
  name: "Streamers",
  methods: {
    ...mapActions(["fetchLive", "fetchInfoGame", "fetchInfoStreamer"])
  },
  created() {
   // this fetch data form the twitch APi for catch the live and store in an 
   // array == Live [{game: null, streamer: null, live:[array of data]}]
    this.fetchLive();
  },
  mounted() {
   //For all the live in the array, this fetch the data about the game and the 
   // streamer
   // first try [{game: null, streamer: null, live:[array of data]}
   // after refresh the dev server 
   // [{game: [array of data], streamer: [array of data], live:[array of data]}]

    this.fetchInfoGame();
    this.fetchInfoStreamer();
  }
};
</script>

I expect fetch all the data only once


Solution

  • mounted and created will not wait for your asynchronous fetching call. There are 2 ways to workaround:

    Solution 1:

    I assumed this.fetchLive() will return a Promise

    data() {
      return {
        this.fetchLivePromise = null
      }
    }
    created() {
      this.fetchLivePromise = this.fetchLive();
    },
    mounted() {
      this.fetchLivePromise.then(() => {
        this.fetchInfoGame();
        this.fetchInfoStreamer();
      })
    },
    

    Solution 2

    I assumed this.fetchLive() will set state liveArray in vuex, then you can by and watching the value when it's available

    computed: {
      ...mapState(['liveArray']),
    },
    watch: {
      liveArray: function(newVal) {
        if (newVal && newVal.length > 0) {
          this.fetchInfoGame();
          this.fetchInfoStreamer();
        }
      }
    }