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

Creating a factory function in TypeScript to generate union types

I have developed a unique Factory type that allows me to create factory functions. export type Factory<T> = (state?: Partial<T>) => T; Within my <Avatar /> React component, I have implemented a prop with a union type to accommodate fo ...

Guide to utilizing props conditionally in a Material UI TextField component

I am looking to build a comprehensive component using Material UI TextField along with Formik While I have managed all other props, I am facing difficulty in dealing with value and onChange, I have tried using 2 functions for onChange, but find it cumber ...

Utilizing the useSearchParams() function to retrieve live data in Next.js

Is there anyone who has successfully migrated from the pages router to the app router in Next.js? I am facing an issue with dynamic data migration. In the pages router, dynamic data is retrieved on a page using useRouter().query, but in the app router, it ...

Use the Vue `this.$router.push` method inside a setTimeout function

I have a landing page '/' that users will see first when they visit our website. I want to display a loading wheel for 5 seconds before automatically redirecting them to the login page '/login'. My Landing.vue page in Vue and Bulma.io ...

Exploring Next.js 13: Enhancing Security with HTTP Cookie Authentication

I'm currently working on a web app using Next.js version 13.4.7. I am setting up authentication with JWT tokens from the backend (Laravel) and attempting to store them in http-only cookies. Within a file named cookie.ts, which contains helper functio ...

Updating the latest version of Typescript from NPM is proving to be a challenge

Today, my goal was to update Typescript to a newer version on this machine as the current one installed is 1.0.3.0 (checked using the command tsc --v). After entering npm install -g typescript@latest, I received the following output: %APPDATA%\npm&b ...

Error: Uncaught TypeError - Unable to assign a value to the 'status' property

Hello everyone, I am currently facing an issue with validating the response from my server using Axios in VueJS. axios.post('/login', { email: this.email, password: this.password }).then(response => { if (response.status == 200) { $ ...

Reverse Vue-router journey

When working with vue-router, is there a way to navigate back using the declarative approach: router-link and router.go(n)? I am aware of the possibility to achieve this by utilizing <h1 @click="$router.go(-1)"></h1>, however, attempting to u ...

Is it possible for Angular2 to map a lone JSON object?

Dealing with a JSON response that is a single object, rather than an array, can be tricky. Recently in my project, I encountered a situation where I needed to map and use such a response from an API to fill out a template. It seemed like a simple task at f ...

Restoring scroll position in Next.js when the page is reloaded

Problem Description I am facing an issue with the sticky header functionality I have implemented. It relies on a useEffect hook to monitor its scroll Y offset state. However, when I reload the page, it fails to detect the position until I manually scroll ...

Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show t ...

Bind Vue.js 2 component's data property to the very first instance of the component or to a single instance only

Seeking assistance. I am relatively new to Vue.js and require some guidance. Scenario: I have a component with BS modal inside, which is rendered in a loop and has multiple instances. Problem: The first rendered component receives its data from the p ...

Building a React Redux project template using Visual Studio 2019 and tackling some JavaScript challenges

Seeking clarification on a JavaScript + TypeScript code snippet from the React Redux Visual Studio template. The specific class requiring explanation can be found here: https://github.com/dotnet/aspnetcore/blob/master/src/ProjectTemplates/Web.Spa.ProjectT ...

Developing Vue applications with dynamic component insertion

Looking to develop a user-friendly form builder using Vue, where users can easily add different form fields by clicking buttons from a menu. If I only had one type of form field to add, it could be done like this (https://jsfiddle.net/u6j1uc3u/32/): <d ...

Managing Visual Studio Code Extension Intellisense: A Guide

I am looking to create an extension I recommend using "CompletionList" for users. Users can trigger completion by running "editor.action.triggerSuggest" The process of my extensions is as follows: Users input text If they press the "completion command," ...

Do these exports serve the same purpose?

Can someone help me understand why one export works while the other doesn't? I've tried to figure it out on my own but I'm stuck. Functioning Example const dataStore = new Vapi({ baseURL: 'http://domain.test/api', state: ...

What steps can I take to ensure that Visual Studio replaces my JavaScript file during the TypeScript build process?

In my development process using Visual Studio to work on my TypeScript project, I have encountered an issue with the build process. I have a build.ts file that links to all of my other TS files and compiles them into one app.js file along with an associate ...

Traversing through pair of arrays simultaneously using forEach loop in JavaScript

I am trying to create a for loop that simultaneously iterates through two variables. One is an array named n, and the other, j, ranges from 0 to 16. var n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22]; var m = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; ...

Typescript: Dynamic return type determined by argument properties

I have a function that should return two different types based on its argument props. interface IPaginateParams { perPage: number; currentPage: number; isFromStart?: boolean; } interface IWithPagination<Data, TParams extends IPaginateParams = IPa ...

Creating a wrapper Vue component in Solara is a simple process that involves encapsulating specific

I need assistance with creating a new Vuejs component in Solara that will wrap its children components. Despite my expectations, the children components are not rendering inside the default slot of the component. How can I modify the code to ensure that th ...