Strategies for managing multiple array filters in Vue JS

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...

Answer №1

If you're looking for a solution in this scenario, consider using a computed prop:

computed: {
  filteredPokemons () {
    if (this.currentType) {
      return this.allPokemon.filter(pokemon => pokemon.types[0].type.name == this.currentType)
    }
    if (this.currentGen) {
      // Assuming there is a prop called 'gen', be sure to replace it with the correct prop name
      return this.allPokemon.filter(pokemon => pokemon.types[0].gen.name == this.currentGen)
    }
    // If both currentType and currentGen are empty, I'm assuming an empty array should be returned
    return []
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating intricate HTML elements through a Chrome content script

Currently, I am utilizing Chrome extension's content script to generate a sophisticated display that is incorporated into web pages. Initially, I tested it by integrating it directly onto a website, but now I want to package it in an extension. The ...

The sorting function in Vue data table is not functioning as intended

In my code, I have implemented a v-data-table: <v-data-table :headers="walletInHeaders" :items="filteredByQuantityIncome" class="elevation-1"> <template v-slot:items="props"> <td class=&quo ...

Insert mustache templates repetitively within a loop

I am having an issue with appending the same mustache template multiple times, each time with different values that are coming from PHP through AJAX. These values are stored in an array. The problem is that every time I append the template, it includes th ...

Ways to show various div elements when a checkbox is clicked

My goal is to have the div element show when I click on the checkbox and hide when I uncheck it. The code below works fine in terms of functionality. However, the issue arises when I click on both checkbox1 and checkbox2, causing the div element to overri ...

Unraveling complex JSON structures in Node.js

I've been working on parsing nested JSON data and here is the code I'm currently using var str = '{"key1": "value", "key2": "value1", "Key3": {"key31":"value 31"}}'; v ...

How can we use JavaScript to convert base 10 colors or hex colors to ANSI colors?

I am searching for a method to convert base 10 colors or hex colors into ANSI colors that are compatible with the terminal. For instance, \u001b[31m represents red in ANSI colors. Any suggestions on how this can be achieved using JavaScript code or a ...

What is the best way to handle a promise passed as parameters to a Subject in RxJS?

When passing a Promise to Subject as a parameter: const work = new Subject<{ id: number; dialogRef: Promise<typeof Dialog> }>(); I aim to utilize the instance inside the promise at a later stage: ... exhaustMap(({ id, dialogRef }) => http ...

React button onclick event not triggering - separate JavaScript file not executing

I have written the code with a separate script file. However, when I click on the buttons next or before, the function nextPrev does not work as expected. All of the JavaScript codes are inside the useEffect, and I am uncertain if this approach is correct. ...

Performing addition and subtraction calculations with HTML and Javascript

I need help creating a simple HTML table for adding and subtracting values, with a limit of 10 and a minimum of 0. I have two functions set up, additionalAdd and additionalSub, triggered by the onclick event, but I keep getting an error saying that totalAd ...

Update an array while monitoring for a specific event

Working with Ionic, my goal is to push an array of an object when a specific event is emitted. This is what I currently have: export class PublicationService { constructor(private storage: Storage) {} private addPublicationSubject = new Be ...

Getting a user's group name from Azure Active Directory in an Angular application - a step-by-step guide

I have connected to Azure directory using ng2-adal (https://github.com/mazhisai/ng2-adal-QuickStart) and successfully obtained a group id in the format: "groups":["4ba2649e-20d2-40f4-a406-2ed897686403","43e19f05-c077-4716-b001-0ffb0d75fff8"]. Is there a w ...

Having trouble getting your jQuery code to work in your HTML document after converting it to

Recently, I've been working with HTML5, CSS, and vanilla JavaScript. I wanted to convert this jQuery code and make some changes to it. However, I seem to be encountering an issue after implementing the new code. The original code had a small triangu ...

Is there a way to showcase a preview of an image within a modal window?

My component is structured like this : <input type="file" ref="file" @change="onFileChange" class="d-none" :accept="accept"> <button type="button" @click="selectFile" ...

JavaScript code that is condensed for efficiency without sacrificing readability and maintainability

As a novice in the world of javascript, I find that studying pre-existing code helps me learn a great deal. I've encountered some extensive javascript projects with minified code that becomes almost indecipherable when expanded. Most variables and f ...

Node.js is indicating that the certificate has expired

When using Mikeal's request library (https://github.com/mikeal/request) to send an https request to a server, I keep encountering an authorization error of CERT_HAS_EXPIRED. request({ url: 'https://www.domain.com/api/endpoint', ...

Conceal the menu on jQuery click event anywhere on the page

There is a button on my interface that, when clicked, opens a menu. The button appears blue when selected and the menu opens, but when a menu item is chosen, the menu closes and the button returns to its original state. However, my problem arises when I ...

Use jQuery to move list items up or down when clicking on an element outside the list, as long as they contain checked checkboxes

I am in need of creating a user interface that includes both a "Move Up" button and a "Move Down" button. These buttons will allow users to reposition list items by moving them up or down within the list, based on whether they click the "Move Up" or "Move ...

The Electron React app crashes due to difficulty parsing the source map

I'm a beginner in the coding world and currently working on creating an electron app using react. One of the functionalities I want to implement in the app is the ability to save user login information so that the data can be automatically fetched whe ...

When I try to run Parcel, my ReactJS website just won't deploy in a serverless environment

For a while now, I've been working on a website using serverless. Everything was going smoothly until this morning when I encountered an issue with pushing updates from my site to the serverless platform. When trying to push, I received the following ...

Nuxt.js does not support Vuex Mutation functionality

Just diving into vuex and nuxt, so there might be a simple solution to this issue. I have two middlewares: one that makes an API call using AXIOS to GitHub and another that pulls from an RSS feed of a medium.com user and converts it to JSON. The mutation ...