Trpimir
Trpimir

Reputation: 25

I'm trying to get and print random pokemon using Api, but it gives me the error 404

This is API site link: https://pokeapi.co/docs/v2#pokemon

This is API example: https://pokeapi.co/api/v2/pokemon/{id or name}/

this is store.js

import { defineStore } from 'pinia'
import axios from 'axios'

let serverHost = 'https://pokeapi.co/api/v2'

export const pokeStore = defineStore("pokemons", {
  state: () => {
    return {
      pokemons: []
    };
  },
  actions: {
    async getOnePokemon(id) {
      try {
        let response = await axios.get(`${serverHost}/pokemon/${id}`)
        if(response.data){
          response.data.name = response.data.name.replace('-', " ");
        let pokemon = {
          id: response.data.id,
          name: response.data.name,
          image: response.data.sprites.front_default
        }
        if(!pokemon.image){
          pokemon.image = response.data.sprites.front_shiny
        }
        return pokemon
      }
      } catch (error) {
        this.getOnePokemon(Math.floor(Math.random() * 151) + 1)
      }
    },
    
  }
});

this is home where im trying to print random pokemon:

```
<script setup lang="ts">
import { RouterView } from 'vue-router'
import { ref } from 'vue'
import { pokeStore } from '../store/store'
const PokemonStore = pokeStore();

let allpokemonsIds = ref<any>()


 async function GetPokemons() {
  try {
    let response = await PokemonStore.getOnePokemon();
    allpokemonsIds.value = response;
    console.log(allpokemonsIds.value)

  } catch (error) {
    throw error;
  }
}

GetPokemons()

</script>

I want to get random pokemon from the first 151 pokemon and print it using the console log in the Home component

Upvotes: 1

Views: 580

Answers (1)

Fogmeister
Fogmeister

Reputation: 77651

Change your code to this...

import { defineStore } from 'pinia'
import axios from 'axios'

let serverHost = 'https://pokeapi.co/api/v2'

export const pokeStore = defineStore("pokemons", {
  state: () => {
    return {
      pokemons: []
    };
  },
  actions: {
    async getOnePokemon() {
      try {
        let id = Math.floor(Math.random() * 151) + 1; // <- I have changed this...
        let response = await axios.get(`${serverHost}/pokemon/${id}`)
        if(response.data){
          response.data.name = response.data.name.replace('-', " ");
          let pokemon = {
            id: response.data.id,
            name: response.data.name,
            image: response.data.sprites.front_default
          }
          if(!pokemon.image){
            pokemon.image = response.data.sprites.front_shiny
          }
          return pokemon
        }
      } catch (error) {
        console.log(error)
      }
    },
    
  }
});

You had some code in the catch that was trying to do the random id nbut that's not where that should go.

I've updated to generate the random id in the function instead of passing the id in.

Upvotes: 1

Related Questions