What's the Reason Behind My Array Populating on Rebuild but Not on Page Refresh?

I am currently utilizing a tech stack that includes Vue 3 with Composition API, a Pinia store, TypeScript, a SQL backend, and Fetch to retrieve data through my .NET 6 API.

Within my codebase, I have a User.ts class:

export default class User
{
    userName: string | null
    
    constructor (userName: string | null)
    {
        this.userName = userName;
    }
}

I am fetching data from the database using the method below:

getAdminUsers(): void
{    
    fetch(apiURL + 'AdminUser',
    {
        headers:
        {
            "Accept": "application/json",
            "Content-Type": 'application/json'
        }
    })
    .then(response => 
    {
        return response.json();
    })
    .then(data =>
    { 
        this.$patch((state) =>
        {
            state.adminUser = { userName: null};
            state.adminUsers = [];
        })

        data.forEach((user: User) =>
        {
            if (user.userName)
            {
                this.adminUser = new User(user.userName.toUpperCase());
                this.adminUsers.push(this.adminUser);
            }
        })
    })
},

While I have had success with other data in my application, I am facing an issue where refreshing the page or running the getAdminUsers method from any part of my Vue app results in an empty array:

[[Handler]]: Object
[[Target]]: Array(0)
length: 0
[[Prototype]]: Array(0)
[[IsRevoked]]: false

Interestingly, making a small change to the app, like adding a space and saving/rebuilding, causes the array to be populated with the correct data:

Proxy {0: User, 1: User}
[[Handler]]: Object
[[Target]]: Array(2)
0: User {userName: 'GEORGE.SMITHSON'}
1: User {userName: 'TEST.2'}
length: 2
[[Prototype]]: Array(0)
[[IsRevoked]]: false

I am struggling to understand why this behavior is occurring and would greatly appreciate any assistance in resolving it.

Answer №1

Without knowing how you are utilizing the array, it is difficult to provide a definitive answer. It appears that your array may not be reacting as expected, leading to the lack of updates until a hot reload occurs. Double check if you are assigning it to another variable and ensure that the variable is also reactive. If you are assigning it, the code should resemble the following:

const store = useAdminStore();
const users = computed(() => store.users);

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

The function was triggered upon the form loading, instead of being activated when the button was clicked

The issue I am facing is that in the code snippet below, the function readCSV() is not being triggered when buttons for filepath1 and filepath2 are clicked. The function is only executed on form load. I was expecting it to work on button click as well. I ...

The jQuery click event not triggering on ASP.NET control

I am currently developing a C#/Asp application that utilizes jQuery. I am trying to implement a specific function that should be called every time a click event is triggered on an element with a class of "loadingInProgress". However, the code snippet belo ...

Accessing the i and i+1 elements within a ng-repeat iteration

I'm currently learning Angular and struggling with a seemingly simple issue. My goal is to achieve the following HTML structure in AngularJS: <div> <div> {{bar[i]}} {{bar[i+1]}} </div> <div> {{bar[i+2]}} ...

When testing my POST request online, it functions properly. However, I am facing difficulties in getting it to work in next.js as I keep receiving a 405

I am currently working on establishing a connection to Zoho Creator in order to retrieve some data. After successfully testing the request on and receiving the correct response, I encountered an issue while trying to implement it within a next.js applicat ...

How to Enhance GraphQL Mutation OutputFields with a Function Generator

I'm encountering issues while trying to incorporate a function generator within a GraphQL mutation. The function generator is utilized to streamline the promise chain inside the mutation. Prior to refactoring the code, everything was functioning corr ...

Reactjs encountering issues with CSS loading correctly

Currently, I am working with reactjs and utilizing the Nextjs framework. All my "css, js, images" are stored in the "public" folder and have been included in "_app.js". However, whenever I attempt to load the "Main page" in a browser, the page does not d ...

Using JavaScript to launch a new window with an array of parameters

I am working on an asp.net mvc 3 application that has an Action Method for handling GET requests and returning a page. The code snippet is shown below: [HttpGet] public ActionResult Print(IEnumerable<string> arrayOfIds) { ....................... ...

The NextJs router encountered an unknown key passed through the urlObject during the push operation

I have a Next.js/React application where I am utilizing the Next Router to include some queries in my URL. However, when using the following function, the Chrome Dev Console displays numerous warnings: const putTargetsToQueryParams = (targets: IFragrance ...

The process of initializing the Angular "Hello World" app

Beginning with a simple "hello world" Angular app was going smoothly until I attempted to add the controller. Unfortunately, at that point, the expression stopped working on the page. <!doctype html> <html ng-app='app'> <head> ...

What exactly happened to my buttons when I transition to the mobile display?

Due to time constraints, I decided to save some time by utilizing a CSS template called Horizons created by Templated. This particular CSS template uses Javascript to adjust the layout for mobile devices, causing buttons to switch from inline to block for ...

Exploring the challenging surfaces of a mesh through raycasting in Three.js

I successfully built a box using three.js var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 100, window.innerWidth/window.innerHeight, 0.1, 1000 ); camera.position.set(5, 5, 10); var geo = new THREE.BoxGeometry(5,2,5); var mat = n ...

Populate the database with values when the button is clicked

Hello, I encountered an issue with my code where it is adding empty values to the database when attempting to enter input text values. I am using PHP and MySQL for this task. <html> <body> <input type="text" name="value" /> <input ...

Countdown component in Ant Design failing to display correct date

I’m currently working on developing a specific date component using react in conjunction with antd. Below is the code snippet I am utilizing: import { Statistic, Col, Row } from 'antd'; const { Countdown } = Statistic; const deadline = Date.pa ...

An issue has occurred with attempting to access the 'phone' property of a null value. This error is at the root of the problem and needs to

I have implemented a function to retrieve all clients from an API: this.ws.getallclients().subscribe( client => { this.client = client.map((clients) => { this.filteredOptions = this.addsale.controls['client_id'].valueChanges. ...

NextJs redirection techniquesWould you like to learn the best ways

Currently, I am developing an application using NextJS with Firebase authentication integration. Upon successful authentication, my goal is to retrieve additional customer details stored in a MongoDB database or create a new document for the customer upon ...

Trigger animation when the scroll position reaches 0.52 in Next.js using framer-motion

I’m working on a landing page and I have a section where I’d like to create a simple opacity animation using framer-motion. The issue is that these animations typically trigger as soon as you land on the page, but I want them to be based on scroll pos ...

What steps should I take to update the image src within my slider?

I have a slider image that I want to fade to the next image when a button is clicked. I used JQuery to create a smooth transition when changing the image source, but the image remains the same after fading. Html <button onclick = "prev()" id = "pr ...

Automatically conceal a div once an iframe reaches a specific height

When a user schedules an appointment on our website, it triggers a change in the height of an iframe. I want to automatically hide the section above the iframe once the iframe's height has changed. Currently, I have implemented the following code whic ...

Using Node.js and Hapi.js alongside Angular.js for web development

Could someone please help me understand how to integrate nodejs (hapi server) with AngularJs? I initially thought that I could intercept all requests made to my Hapi server and handle them using angularjs routes / REST, but it seems like I'm encounter ...

What is the contrast between element.getAttribute() value and a String in protractor?

When using protractor and typescript, I need to verify that the text saved in a textbox matches a certain string by comparing it with the resulting value of element.getAttribute("value"). Unfortunately, getText() does not work for this scenario b ...