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>❮</button>
<button>❯</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.