When a const variable is declared within the composition-api setup(), it remains unchanged unless redeclared within the function scope

Being primarily a back-end developer, the front-end side of things is still relatively new to me. I'm aware that there are concepts in this domain that I haven't fully grasped yet, and despite my efforts, I'm unable to resolve a particular issue.

In Vue (version 3), I have a component that receives an array prop from its parent. Since props are not directly mutable, I assign this prop to a const variable for manipulation. Within the setup(props) function using the composition API, I have declared this const at the beginning. In a sort function within the setup, I modify the contents of the prop by emptying it with splice and then fetching new data from the backend to push into the array.

However, this approach doesn't seem to be effective. Strangely enough, it works when I declare the const inside the sort function itself. Examples provided below:

setup(props) {
  const xs: x[] = props.x;

  //Called on @click event
  async function toggleSortByProperty(property: string) {
    const ys = await axios.dosomething();

    xs.splice(0);
    xs.push(...ys)
  }
}

The above code snippet doesn't yield the desired outcome. Surprisingly, if I move the declaration of const xs just below the toggleSortByProperty line, everything seems to work magically. However, this workaround isn't ideal since I intend to use the variable in multiple functions within the setup.

Here are some additional observations:

  • Upon hot-reloading (after saving changes), the functionality starts working again;
  • It appears that the xs variable remains undefined for the initial click event but becomes defined thereafter, potentially causing issues.

I find myself somewhat puzzled by this situation. Any insights or suggestions would be appreciated.

Edit:
While revising this post, I attempted to address the problem concurrently and managed to identify the root cause. It was simply a lapse in judgment on my part. As it turns out, the child component was being created before 'x' was populated properly. Recently, I had replaced a v-if directive with a b-overlay (BootstrapVue) in the parent component, which merely concealed the child component instead of delaying its creation. This explains why moving the 'xs' declaration inside the toggle function resolved the issue.

Answer №1

To improve the organization of your code, consider placing the xs variable inside a computed function when returning it like so:

return {
xs:computed(()=>xs)
}

Alternatively, based on the logic you have described, I recommend avoiding making this request in this component. The parent component, responsible for sending the main result, should handle operations such as sorting and filtering. Your component can focus on displaying data, making it clearer and easier to unit test.

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

How does using ngFor and ngModel in Angular cause a change in one select to affect others?

I am looking to implement a feature where users can create multiple select dropdowns, choose options for each one, and then aggregate these selections into an array that will be sent to a parent component. My current approach involves using an *ngFor loop ...

Automating the scrolling function in Angular 2 to automatically navigate to the bottom of the page whenever a message is sent or opened

In my message conversation section, I want to ensure that the scroll is always at the bottom. When the page is reopened, the last message should be displayed first. HTML: <ul> <li *ngFor="let reply of message_show.messages"> ...

Creating a TypeScript function that automatically infers the type of the returned function using generics

Suppose I want to execute the generateFunction() method which will yield the following function: // The returned function const suppliedFunction = <T>(args: T) => { return true; }; // The returned function // This is how it can be used suppli ...

Accessing collection values from referenced document IDs in Firestore---I have provided a unique version of the text

I have two fire store collections with the following reference images: . I am trying to retrieve the firstName and title from these collections. The signup_id is referenced from the document id of coll-signup. Below is the code snippet of what I have done ...

Troubleshooting Issue: Running Parent Vue Methods in Framework 7 Vue not Functioning as Expected

Despite trying numerous approaches to execute a simple function from a parent Vue component, I am still facing issues. Console.log shows no errors, but nothing seems to happen. Can anyone please lend a hand with this? Thank you in advance. app.vue import ...

Nuxt Static Site encountering issues with displaying dynamic content on 404 Error page

Edit I recently resolved the issue of the error template not loading correctly by fixing an htaccess problem. By adjusting the ErrorDocument to be /sub/dirs/error.html (without the dist folder), I was able to get it to work properly. However, I am still fa ...

Example of TypeScript Ambient Namespace Usage

The Namespaces chapter provides an example involving D3.d.ts that I find puzzling. Here is the complete example: declare namespace D3 { export interface Selectors { select: { (selector: string): Selection; (element: ...

Retrieving locale messages by accessing the app context from customized .js files

Currently, I am developing a Vue.js application with Nuxt.js in SSR mode. The project includes plugins such as axios and vue-i18n. nuxt.config.js : export default { mode: 'universal', // additional configurations modules: [ '@nuxt ...

What is the method for generating an observable that includes a time delay?

Question In order to conduct testing, I am developing Observable objects that simulate the observable typically returned by an actual http call using Http. This is how my observable is set up: dummyObservable = Observable.create(obs => { obs.next([ ...

Tips for configuring TypeScript in a monorepo to successfully compile private packages

I have configured a monorepo using turborepo that includes Nestjs for the backend and Nextjs for the frontend. To reuse prisma definitions, I separated them into their own package with its own tsconfig. In the index file of my database package where prism ...

What is the process for toggling a button using Vue.js?

Important Note: Implemented Vue.js and Vuetify.js for both functionality and styling. Utilizing the :class and @click properties, I managed to alter the background color of a button to a specified color. However, this modification is being applied to all ...

How can one determine the data type by analyzing the key value?

I'm attempting to determine the return type of getAllRaces() as () => Race[]. Here is what I have tried so far: type CollectionMap = { races: Race[] horses: Horse[] } type Race = { date: Date } type Horse = { name: string } typ ...

The integration of cypress-cucumber-preprocessor with multiple testing frameworks appears to be experiencing compatibility issues

I am trying to set up a connection between Cypress and Cucumber, and I came across this plugin: https://www.npmjs.com/package/cypress-cucumber-preprocessor However, I am having trouble with my implementation as it seems to be missing. I have also added th ...

Upgrading from Vue.js 1.x to 2.x: Understanding the Compilation Process

Code snippet 1: It seems to be functioning properly. this.$compile(this.$els.ajaxcontent); Migration notes: this.$compile(this.$refs.ajaxcontent); // Issue encountered: $compile function not found. Vue.compile(this.$refs.ajaxcontent); // Problem: temp ...

Utilize apexcharts to apply custom colors for negative data points

I am currently utilizing apex charts within a react application, and I have a requirement to display markers with different colors if the y value is a negative number. Below is the logic that I am using to extract the values: const colorMarkers = ...

Steps to disable TypeScript error messages for unused variables

I encountered an issue in my Angular CLI that says: jest.config.js is part of the TypeScript compilation but it's unused. Add only entry points to the 'files' or 'include' properties in your tsconfig. Additionally, I have a few o ...

Utilizing the power of generics alongside index type manipulation

After successfully running this code: const f = <T extends string>(x: T) => x; f(""); interface Dictionary<T> { [key: string]: T; } const dict: Dictionary<number> = { a: 1 }; I anticipated the following code to work as well: interf ...

Rendering content on the server side or pre-rendering in Laravel and Vuejs

I am working on a web application using Laravel 7 and Vuejs2. The website has several important pages including home, about, cities, and help that need to be visible to search engines. I have tried implementing both prerendering and server side rendering b ...

Angular does not recognize the boolean variable

Within my Angular component, I have declared two boolean variables: editingPercent: boolean = true; editingCap: boolean = false; In the corresponding HTML file, there is a checkbox that updates these variables based on user input: checkedChanged(e) { ...

Learn how to dynamically display data without the need for refreshing using Vue.js and Laravel

I am looking for a way to display the data that I have successfully inputted into the database without having to reload the page or change components immediately. My current setup involves using vue.js within the Laravel 5.8 framework, along with axios an ...