Uncertain about when to utilize computed properties versus watch functions to showcase my data. Currently, I am developing an application with the PokeAPI and aiming to switch between Type and Generation to exhibit the Pokémon. In my JS file, I have a storage of all the Pokémon in an array:
//pokeData.js
import axios from 'axios'
const allPokes = [];
export default{
getPokemon(){
if(allPokes.length === 0){
for(let i=1; i<=809; i++){
axios.get(`https://pokeapi.co/api/v2/pokemon/${i}`)
.then(response => {
allPokes.push(response.data);
allPokes.sort((a, b) => a.id - b.id);
});
}
}
return allPokes
}
}
Avoiding repeated calls for 809 objects from an API, I fetch them in mounted() within my Vue file, intending to filter from that point:
//Container.vue
//accepts two props, 'currentType' and 'currentGen', for filtering the Pokémon
<template>
<div
v-for="(pokemon, index) in allPokemon"
:key="index">
<h2>{{ pokemon.name }}</h2>
</div>
</template>
<script>
import Pokemon from '../pokeData'
export default {
props: ['currentType', 'currentGen'],
data(){
return{
allPokemon: [],
}
},
mounted(){
this.allPokemon = Pokemon.getPokemon();
},
watch: {
currentType: function(newType){
const typePokes = this.allPokemon.filter(pokemon => {
if(pokemon.types[0].type.name == newType){
return true
}
this.allPokemon = typePokes
});
I realize there's an issue here, but I'm unsure how to rectify it. It's known that you can utilize List Rendering as suggested in the official documentation, yet it doesn't provide guidance on employing it for multiple filters. https://v2.vuejs.org/v2/guide/list.html#Replacing-an-Array
Any suggestions are appreciated: whether on optimizing the initial API call caching, utilizing watch or computed properties...