Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

418
Visualizações
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 } ].

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda