Is the value of the incorrect store ref in Vue3 being altered?

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?

Answer №1

It's difficult to say for certain without a minimal reproducible example, but it appears that the issue may lie in how you are defining the filteredData variable. It seems like you are omitting the use of .value, causing filteredData to simply reference the "ref" countriesData, leading to both variables being updated simultaneously.

To ensure that these two variables are separate entities, consider performing a deep copy of the countriesData array into the filteredData variable using the spread syntax.

export const filteredData = ref([...countriesData.value]);

This approach guarantees that the filteredData reference contains only a duplicate of the array present in countriesData.

Additionally, don't forget to include the await keyword before calling your getData() function.

Answer №2

By assigning filteredData as a reference to countriesData, you are essentially linking them together. This means that any changes made to filteredData will also affect countriesData. To prevent this, you should create a copy of countriesData if you want to store it in filteredData.

const filteredData = ref([...countriesData.value])

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

Formik state is mysteriously reverting field values to their default state

I've encountered an issue with my form and song state while trying to add a new field called "appleMusicId". Unfortunately, every time I add this field, it seems to reset the values of timeDescription and sceneDescription. I've spent hours tryin ...

Generate Pagination in JavaScript using an Array of Elements

Is there a way to implement a Pagination System using JavaScript? Specifically, I need to display 10 products per page. I currently have an Array containing various products and my goal is to iterate through these products to display the first 10 on one p ...

Autocomplete feature in Angular not showing search results

I am currently using ng-prime's <p-autocomplete> to display values by searching in the back-end. Below is the HTML code I have implemented: <p-autoComplete [(ngModel)]="agent" [suggestions]="filteredAgents" name="agents" (completeMethod)="f ...

CORS problem in Chrome when using AngularJS and Symfony 3

I've been dealing with a bug on my backend and frontend for the past week. I created a REST API (php/symfony) to manage books and authors. Initially, I had trouble with cross-origin requests on DELETE, which has been resolved. However, now I am facin ...

Guide on implementing a personalized 'editComponent' feature in material-table

I'm currently integrating 'material-table' into my project. In the 'icon' column, I have icon names that I want to be able to change by selecting them from an external dialog. However, I am encountering issues when trying to update ...

The parseFloat function only considers numbers before the decimal point and disregards

I need my function to properly format a number or string into a decimal number with X amount of digits after the decimal point. The issue I'm facing is that when I pass 3.0004 to my function, it returns 3. After reviewing the documentation, I realized ...

What is the reason that setState functions properly when parsing each key separately, but fails when passed as an object?

Currently, I am delving into the world of React and TypeScript, but I have encountered a problem when trying to pass an object with a specific type in order to update the state. For some reason, the state remains unchanged. My approach involves using the ...

What is the method for setting the doctype to HTML in JavaScript or React?

I created a canvas with a height equal to window.innerHeight, but unexpectedly it seems to have 100% screen height plus an extra 4 pixels coming from somewhere. I came across a solution suggesting that I need to declare doctype html, but I'm unsure ho ...

Encountering a problem when trying to submit data on a form in Prisma Nextjs due to an

As I construct an editing feature for objects within my postgres database, I am encountering an issue related to form submission. Specifically, when attempting to update fields defined in the schema, I am receiving an error message: client_fetch_error unde ...

Converting Markdown to HTML using AngularJS

I'm utilizing the Contentful API to retrieve content. It comes in the form of a JSON object to my Node server, which then forwards it to my Angular frontend. This JSON object contains raw markdown text that has not been processed yet. For instance, t ...

Retrieve both the name and id as values in an angular select dropdown

<select (change)="select($event.target.value)" [ngModel]="gen" class="border border-gray-200 bg-white h-10 pl-6 pr-40 rounded-lg text-sm focus:outline-none appearance-none block cursor-pointer" id="gend ...

"How can I open a DOCX file in a new window using JavaScript and then close the window

When attempting to open a doc/docx file in Word from an HTML link, my goal is to prevent the opening of a new browser window. First attempt: mywin=window.open("filename.docx","viewer"); The first attempt works fine, but it results in opening a new "view ...

Using jQuery to create a seamless scrolling experience to both the top of a page and to

I've been looking for solutions on how to add both jQuery scroll to top and scroll to anchors, but haven't found any integrated options. Is it possible to achieve this here? We currently have a jQuery function in place to add a scroll-to-top fea ...

Tips on positioning content beneath a fixed header or navigation bar when viewed in a web browser

Hi, I'm having an issue with creating a fixed header using HTML and CSS. When I set my header to be in a fixed position, it covers up the content below it. I want the content to be positioned under the header when the page is loaded. Additionally, I&a ...

Direct AngularJS to automatically reroute users from the login page to the welcome page

I am currently developing a web application where I need to redirect from the login page to the welcome page once the user id and password have been validated. <script> var app = angular.module('myApp', []); app.controller(&apo ...

Offering various language options on a website determined by the URL

I've been contemplating how to add multi-language support to my personal website, which I developed using ExpressJS and NodeJS with EJS as the template engine. Currently, the website is only available in English, but I want to add a German version as ...

Displaying Vue.js tooltips in a table when the text gets clipped

I'm currently facing an issue with creating a tooltip in my vue.js document. I attempted to follow this guide from https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_tooltip in order to create one, but it's not working as expected. Her ...

CSS- Strategically placing and centering images above specific keywords in (any) HTML content without disrupting the flow of text

My main objective involves dynamically inserting images above text on any given page using a content script. The challenge lies in maintaining the proper alignment of the text after adding the images. To achieve this, I surround the words where the image i ...

Position object in the middle using jQuery and CSS

Trying to center an absolutely positioned object horizontally using CSS and jQuery is proving to be a challenge. The use of jQuery is necessary due to the varying widths of the objects. Hover over the icons in my jsFiddle to see the issue. Check out the j ...

While the Mongoose aggregate query is functioning properly in MongoDB, I am encountering difficulties in converting it to a Mongoose

Here is the JSON structure provided: [{ "_id" : ObjectId("626204345ae3d8ec53ef41ee"), "categoryName" : "Test Cate", "__v" : 0, "createdAt" : ISODate("2022-04-22T01:26:11.627Z"), "items" : [ { ...