Refreshing the page after making an API call does not result in updated data

Within my VueJS application, I have implemented an API call to retrieve user statistics for display. The process involves a straightforward Java backend and utilizing an $axios get request. Upon initial page load, everything functions as anticipated. However, upon navigating away from the page and returning or updating the content, the displayed values reset to 0.

I suspect that this issue stems from the DOM not being properly updated for some reason. Despite observing successful API calls in the "Network" tab of the developer tools, the data retrieved is not reflected on the page.

<template>
  <div>
    <h3>Users:</h3>
    <v-container class="grey lighten-5">
      <v-row
        v-for="(d, index) in data"
        :key="index"
        no-gutters
      >
        <v-col>
          <v-card
            class="pa-2"
            outlined
            tile
          >
            {{ d.title }}
          </v-card>
        </v-col>
        <v-col>
          <v-card
            class="pa-2"
            outlined
            tile>
            {{ d.value }}
          </v-card>
        </v-col>
      </v-row>
    </v-container>
  </div>
</template>

<script>
import {Component, Vue} from "vue-property-decorator";

@Component({
  created() {
    this.$accessor.users.loadNumOfNewUsers()
  },
  mounted() {
    this.newUsers()
  }
})
export default class ShowNewUsers extends Vue {
  data = [
    { title: "New users:", value: -1 },
  ]

  newUsers() {
    Vue.set(this.data[0], "value", this.$accessor.users.newUsers);
  }
}
</script>

The API calls, such as

this.$accessor.users.loadNumOfNewUsers()
and this.$accessor.users.newUsers, are directed towards my Java backend through the following code snippet, which seems to be operational without issues:

import {actionTree, getterTree, mutationTree} from "typed-vuex";

export const state = () => ({
  newUsers: 0,
});

export type AdminState = ReturnType<typeof state>;

export const getters = getterTree(state, {
  newUsers: (state: AdminState) => state.newUsers,
});

export const mutations = mutationTree(state, {
  setNumOfNewUsers(state: AdminState, numOfNewUsers) {
    state.newUsers = newUsers
  }
});

export const actions = actionTree(
  {state, getters, mutations},
  {
    async loadNumOfNewUsers({commit}) {
      const numOfNewUsersUrl = '/api/my/java/backend'
      await this.$axios.get(numOfNewUsersUrl).then((response) => {
        commit('setNumOfNewUsers', response.data)
      })
    },
  },
);

Considerations regarding potential use of the @Watch decorator arise, but my understanding suggests it is unnecessary for simple page reloading. Additionally, the unexpected conversion of the displayed value from -1 to 0 hints at a JavaScript anomaly, possibly involving NaN. At present, I am uncertain of the exact cause.

Answer №1

To address this issue without utilizing TypeScript, one alternative approach is to develop `computed` and `watch` modules. The `computed` module can be created to monitor when fetching the value and updating it accordingly. Subsequently, the `items` data variable can be updated using the `watch` module, which triggers a response upon detection of the change and subsequently updates the variable for display.

<template>
  <v-data-table
    :headers="headers"
    :items="items"
    :items-per-page="5"
    class="elevation-1"
  ></v-data-table>
</template>

<script>
export default {
  name: "NewUsers",
  data: () => ({
    headers: [
      {text: 'What', value: 'what'},
      {text: 'Number', value: 'num'}
    ],
    items: []
  }),
  computed: {
    getNewUsers() {
      return this.$accessor.admin.newUsers
    }
  },
  watch: {
    getData() {
      this.items.push({what: 'Number of new users', num: this.getNewUsers})
    }
  },
  mounted() {
    this.$accessor.admin.loadNumOfNewUsers()
  },
}
</script>

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

What are the steps to troubleshoot a Node Package Manager library in Visual Studio Code?

I have created a Typescript library that I plan to use in various NodeJS projects. The source code is included in the NPM package, so when I install it in my projects, the source also gets added to the node_modules folder. Now, during debugging, I want to ...

Is there a way to retrieve the contents of a vue component (such as a modal window) when clicking a button that is located within a different vue component?

I'm in the process of organizing my basic Vue application into components. I have a product listing where each item has some information and a button. When the user clicks on the button (referred to as the "more details" button), a modal window opens ...

Atom-typescript does not always successfully compile all typescript files to JavaScript

Currently, I am in the process of learning how to implement routing in Angular2 by following a tutorial. The tutorial involves creating partial pages using .ts files along with companion .js files for each page. While my Atom editor, equipped with atom-typ ...

Utilizing Laravel and Vue.js: Incorporating Blade/PHP variables within Vue variables within Laravel Blade Templates

While it may seem like a bit of overengineering, I haven't been able to think of another solution. I am fetching a model using axios. The model has an English title and potentially a localized alternative title. The code provided below is functional, ...

Implementing the same concept yet yielding diverse variations?

I'm a bit confused as to why a1 is evaluated as false while a2 is considered to be of type boolean. Can someone explain the reasoning behind this discrepancy? type Includes<T extends readonly any[], U> = U extends T[number] ? true : false; type ...

Combining d3 and vue.js for enhanced interactive visualizations

I am currently in the process of integrating D3 with vue.js and I am following a straightforward guide available here: The guide suggests appending a new div for each new bar, which I have successfully accomplished using a custom directive as shown in the ...

Is it possible to manipulate an Angular #variableName in order to retrieve an ElementRef for an HTML element?

Suppose I have a scenario where I create a button like this: <button #myButton>My Button</button> ...and then use ViewChild in the following way: @ViewChild('myButton', { static: true }) createButton: ElementRef; In this case, creat ...

Combining declarations to ensure non-null assets

Let's modify this from @types/aws-lambda to clearly indicate that our intention is for pathParameters to not be null and have a specific format. export interface APIGatewayProxyEventBase<TAuthorizerContext> { body: string | null; headers ...

Hide react component by clicking it

There is a cookies component with a button labeled "I agree" that I want to use to close the component when clicked. However, I am facing an issue in getting this functionality to work. I understand that the onClick event on the button should trigger an ...

How can Karma unit tests with Jasmine in a TypeScript Node project accurately measure code coverage, even with external dependencies?

We have a unique situation with the code coverage of our project involving a node dependency. It's important to note that the npm dependency source code is actually part of our project, as we are responsible for its development and publication. Here&a ...

Removing duplicate entries in child components fields using Vue JS

I am facing an issue with a child component that retrieves repeating data from an Axios request. List of Colors: blue, blue, red, orange, green, green, blue Child Component <div v-if="color"> <strong> Color:</str ...

Best practice for incorporating Bootstrap into Webpack

Greetings everyone, I've been experimenting with Bootstrap for Webpack, but I've hit a roadblock. After reading numerous blog articles, I found that they either rely on the outdated 'bootstrap-webpack' plugin from 7 months ago (which d ...

Angular Bootstrap Datepicker provides us with a date object, but I need it in the Date format

My desired date format is "Wed Aug 07 2019 16:42:07 GMT+0530 (India Standard Time)", but instead I am receiving { year: 1789, month: 7, day: 14 } from ngbDatepicker. Any assistance on resolving this issue would be greatly appreciated. ...

How many times can vue.js v-for iterate through a variable?

Looking to loop through rows in a table using a range? Most examples show how to do this for a fixed value, like: <div> <span v-for="n in 10">{{ n }} </span> </di But what if you want to achieve this with a variable like below? &l ...

The issue of resolving custom paths imports in Typescript has been a persistent challenge for developers

Currently, I am developing a project in PHP and utilizing Typescript. I aim to follow a monorepo pattern similar to what NX offers. However, I am facing challenges when attempting to compile typescript for each of my apps. Here is the current structure of ...

TypeScript's Named Type Association

In my project, I have implemented a system that connects names to specific types through a Mapping Object Type called TMap The purpose of this system is to provide a handler function with information about one of the named types along with its correspondi ...

Exploring Vue Slots: A guide to parsing and rendering slot components

Currently facing a challenge while developing a web page using Vue, specifically with parsing and rendering the child components inside the <slot>. I need to extract the slot content, convert it into an array of components, and display these compo ...

What is the method for reaching a service in a different feature module?

Currently, I am utilizing Angular 2/4 and have organized my code into feature modules. For instance, I have a Building Module and a Client Module. https://i.stack.imgur.com/LvmkU.png The same structure applies to my Client Feature Module as well. Now, i ...

Vuetify displaying incorrectly following deployment

After creating a spa with vue.js for the frontend, I utilized the vuetify library for various components and layout. While everything looked great locally, upon deploying to Azure, all vuetify styling seemed to disappear. My custom css was still applying ...

Update the total in the input field by aggregating data from multiple input fields in a Vue2 component

When receiving a response from an API, I am generating a variable number of input fields for product quantity. Each input field takes a number as input and I need to update the total price for each item and the subtotal for all items when the user changes ...