What is the best way to display a Vuex state based on a function being activated?

I have noticed similar questions on this topic but couldn't find a solution, so I decided to create my own.

Here's the issue: I have an array named "allCountries" in the state, initially filled with 250 country objects. I am successfully rendering these countries in my home component. However, I want to filter them based on the continent when a corresponding button is clicked. For example, if the button says "Europe", I want to display all countries where the "continent" property is Europe.

To achieve this, I am using the following code:

const store = createStore({
state: {
    allCountries: [],
    filteredCountries: [],
    countryId: {},
},

mutations: {

    filterByContinent(state, payload) {
        let countries = [...state.allCountries];
        state.filteredCountries = countries.filter(
            (country) => country.continent === payload
        );
    },
},

The problem arises when trying to render the filtered countries upon clicking the button. In the Vuex dev tools, I can see that the "filteredCountries" state is correctly populated with countries of the selected continent upon clicking.

I have tried the following but it's not working:

<template>
<div>
    <ul class="countriesBox" v-if="allCountries">
        <li
            v-for="country in allCountries"
            :key="country.id"
            class="countryCard"
        >
            <br />
            <p class="countryName">{{ country.name }}</p
            >

            <p class="countryContinent">{{ country.continent }}</p
            >

            <img
                :src="`${country.flagImage}`"
                alt="country flag"
                class="flagImage"
            />
        </li>
    </ul>
    
    <ul class="countriesBox" v-else-if="filteredCountries">
        <li
            v-for="country in filteredCountries"
            :key="country.id"
            class="countryCard"
        >
            <br />
            <p class="countryName">{{ country.name }}</p
            >

            <p class="countryContinent">{{ country.continent }}</p
            >

            <img
                :src="`${country.flagImage}`"
                alt="country flag"
                class="flagImage"
            />
        </li>
    </ul>

    <div class="backAndForwardButtons">
        <button>&#10094;</button>
        <button>&#10095;</button>
     </div>

 <FiltersBar />
</div>
</template>

I have correctly mapped the states with

import { mapState } from "vuex";
import store from "../store";

export default {
    name: "HomePage",
    computed: {
        ...mapState(["allCountries"]),
        ...mapState(["filteredCountries"]),
    },
};

If anyone could provide some help, I would greatly appreciate it.

Answer №1

To simplify your code, you can create a getter that checks if there is a `.length` property in `filteredCountries`. If it doesn't exist, then default to using `allCountries` instead. Here's an example:

countries(state) {
  return state.filteredCountries.length ? state.filteredCountries : state.allCountries
}

This way, in your component, you only need to use one data source named `countries` instead of duplicating the logic to render two separate lists from different sources.

Answer №2

If you're looking to retrieve filtered countries in your store, you could implement a method like the one shown below:

filteredCountries: (state) => cont => {
      return state.countries.filter(country=>{
       return country.continent===cont
    })
}

While this code may not be exact, the concept remains consistent.

Notice that the filteredCountries getter includes an additional argument which specifies the selected continent.

In your component, you can initialize the continent filter as follows:

data(){
   return {
       cont_filter:"europe"
   }
}

Changing the value of cont_filter upon button click should not pose a challenge, as that is the intended behavior. You can now use it in the following manner:

    <li v-for="country in filteredCountries(cont_filter)"
                :key="country.name">
        {{country.name}}
   </li>

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

What are the steps for pairing jsplumb with vuejs?

I successfully implemented the jsPlumb script in an .html file within the script tag and it is functioning properly. <body> <div id="q-app"></div> <!-- built files will be auto injected --> <script> jsPlumb.rea ...

My stored variable in the php session is not being recalled properly

Currently, my PHP script is generating new files based on user input. I want all documents to be created using the initial input to ensure consistency. In the first PHP script, I set the variable as follows: session_start(); $_SESSION["FirstName"] = $_POS ...

Is jQuery capable of appropriately escaping my quotes?

Currently, I am utilizing $.cookie() to retrieve all the values from a cookie which are stored in JSON format: var properties = $.cookie('params'); The output of properties is: {"distinct_id": "13f97d6600b42e-000e6293c-6b1b2e75-232800-13f97d66 ...

What is the best way to utilize unique slash commands in Slack threads?

After setting up a custom slash command /news in Slack, it appears to work fine. However, I'm struggling to figure out how to trigger slash commands within threads. Whenever I try to use the command, I receive this error message: /news is not support ...

VueJS: Transforming Date Formats from Backend to Frontend

I have a scenario where I need to format a date retrieved from the backend before displaying it on the frontend. The data is being presented in a table structure as shown below: <vue-good-table :columns="columns" :rows="formatedItems" : ...

Toggle Vue transitions on and off with a boolean parameter

Is there a way to dynamically disable a transition animation in Vue based on a boolean value? Currently, the animation is enabled with the following code: <transition name="fadeUp"> <div v-if="elIsVisible"> <p>Foo Bar</p> ...

Retrieve Data from MySQL Database Using ExpressJS Pool Connection

I am relatively new to ExpressJS. I am encountering an issue where console.log is working fine and I can see the data in the terminal when I make a call. However, the data is not being returned as a response. Even after using console.log and return stateme ...

Unable to populate an array with JSON elements within a for loop triggered by useEffect

In my code, there is an issue with the array candleRealTimeDataQueue not updating correctly. Below is the snippet of the problematic code: let candleCurrentJSONDataWS = null; var candleRealTimeDataQueue = []; let tempDateTime = null; let ca ...

What strategies can be used to effectively structure CSS and JavaScript in a project for optimal organization?

In my NetBeans project, I currently have a large web project with CSS files included in the header. Some CSS codes are needed on all pages, while others are only necessary for specific pages. I am looking to optimize high-traffic pages by removing any ...

Issue with datetime picker in JavaScript/jQuery: Input fields added dynamically are not showing the datetime picker

I am currently investigating why the datetime picker does not work on a dynamically added input block within a table cell. A code snippet below serves as a proof of concept for this issue. In its present state, the default input tag (id: dti1) functions co ...

Enclosing values in JavaScript literals

I apologize for the inconvenience. I am unsure why it is not functioning properly. If I input <button type="button" onclick="document.getElementById("demo").innerHTML = Date()">click</button> the above code does not work. However, if I u ...

What is causing the Angular-UI TypeAhead code to display all items instead of filtered items?

I have been experimenting with the angular-ui typeahead directive to create a filtered input box that only shows items based on what has been typed. However, my current code is displaying all the items instead of just the filtered ones. If you'd like ...

Why is it impossible for me to show the title "individual name:"?

<p id="display1"></p> <p id="display2"></p> var player1= { alias: 'Max Power', skills: ['shooting', 'running'] }; $("#display1").append( "<br/>" + "player alias :" + player1.alia ...

Various array outcomes are produced by identical JavaScript (SAP UI5) code

Utilizing cachebuster to identify the modified file in the application structure. Javascript code snippet: https://i.sstatic.net/CZGfW.png Ineffective Array result: https://i.sstatic.net/D6MdS.png Effective Array result: https://i.sstatic.net/pQCIh.p ...

Tips for resolving the issue of 'no serverless pages built' during deployment of a Next.js application on Vercel

Recently, I've been encountering the same two errors while trying to deploy my NextJs app: // and will just error later on Error: No serverless pages were built. You can learn more about this error here I'm stuck and unsure of how to resolve bo ...

The integration of ngx-translate with an HTTP interceptor is currently experiencing difficulties

Using ngxtranslate for application translation has been seamless so far. However, I am facing an issue with the HttpInterceptor. This interceptor attempts to retrieve data from local storage at the start and displays a dialog prompting you to either load t ...

Customize CKEditor by automatically changing the font family when the page is loaded

How can I change the font-family of CKEditor to Meiryo based on a JavaScript boolean? I attempted this code in my custom JS within an if condition, but it did not successfully change the font-family: config.font_style = { element : 'span&apo ...

Issue with activation of onClick event in case/switch statement

Currently working on a JavaScript project to recreate the Fallout terminal game, with one of the main aspects being comparing words selected by the user to those chosen by the computer. The concept of this hacking game is reminiscent of the board game Mas ...

Is it possible to switch from kilometers to miles on the distance matrix service in Google Maps?

let distanceService = new google.maps.DistanceMatrixService(); distanceService.getDistanceMatrix({ origins: [sourceLocation], destinations: [destinationLocation], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.IMPERI ...

Enhance Your Website with HTML and JavaScript

Here is the code snippet I am working with: sTAT **javascript** var acc = document.getElementsByClassName("item-wrapper"); var i; for (i = 0; i < acc.length; i++) { acc[i].onclick = function(){ this.classList.toggle("selected"); this.nextElementS ...