Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get random data from API

I’m trying to get random id from data obtained through an api in vuejs. Then i’m trying create a code like this.

data() {
   return {
     mostPlayed: [],
     randomData: [],
   }
},
created() {
   this.randomData = this.randomItem(this.mostPlayed);
},
methods: {
   async getMostPlayed() {
      try {
        const response = await axios.get(url);
        const data = response.data.slice(0, 9);
        this.mostPlayed = data;
      } catch (error) {
        console.log(error);
      },
   randomItem (items) {
      return items[Math.floor(Math.random() * items.length)];
    }
},
mounted() {
   this.getMostPlayed();
}

Sample data

[ 
 {
   id: 1
   title: "Forza Horizon 5"
 },
 {
   id: 2
   title: "Apex Legends"
 },
 {
   id: 3
   title: "Battlefield 2042"
 },
 {
   id: 4
   title: "Fortnite"
 },
 {
   id: 5
   title: "Genshin Impact"
 },
]

But nothing happened. I want to get random id with sample data like that. Example output like this. [ { id: 3 }, { id: 1 }, { id: 5 } ].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are calling method for API call in mounted and generating the random list from the most played list in created. But as per the lifecycle diagram of vue given here, you can see that created hook comes first and then mounted hook. So that way you are creating random list on an empty most played array.

As a solution call the getMostPlayed method inside created and randomItem method inside getMostPlayed after API response.

Something like this :

data() {
    return {
        mostPlayed: [],
        randomData: [],
    }
},
created() {
    this.getMostPlayed();
},
methods: {
    async getMostPlayed() {
         try {
             const response = await axios.get(url);
             const data = response.data.slice(0, 9);
             this.mostPlayed = data;
             this.randomData = this.randomItem(this.mostPlayed);
         } catch (error) {
             console.log(error);
         },
    randomItem (items) {
         return items[Math.floor(Math.random() * items.length)];
     }
}

Please refer to answers to this question if you want to have multiple random elements as current logic is to get a single random element from an array : Get multiple random elements from array

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading