Welcome to the store:
import { ref } from "vue";
// Storing all the country data
export const countriesData = ref();
export const isLoading = ref(true);
async function fetchData() {
try {
isLoading.value = true;
const response = await fetch("https://restcountries.com/v3.1/all");
const data = await response.json();
countriesData.value = data;
} catch (error) {
console.error("error", error);
} finally {
isLoading.value = false;
}
}
fetchData();
// Store for filtered data
export const filteredData = ref(countriesData);
The countriesData is set once with the async fetchData() and remains unchanged. However, the filteredData can change based on search queries in the application.
Here's a snippet of code for handling search input:
<script setup>
import { ref } from "vue";
import { countriesData, filteredData } from "../../store/store";
const searchValue = ref("");
function handleSearch(e) {
e.preventDefault();
for (let i = 0; i < countriesData.value.length; i++) {
if (
countriesData.value[i].name.common.toLowerCase() ===
searchValue.value.toLowerCase().trim()
) {
filteredData.value = [countriesData.value[i]];
searchValue.value = "";
return;
}
}
}
</script>
After running the above loop successfully, I notice that both filteredData and countriesData are being changed unexpectedly. When assigning countriesData value to filteredData inside the loop, it also affects countriesData itself. Commenting out this line leaves countriesData unchanged.
It seems like the line
filteredData.value = [countriesData.value[i]];
is causing unwanted changes to both stores. How can I ensure that only filteredData updates without modifying countriesData?