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

Encountering difficulties with installing TypeScript

I am facing an issue while trying to install TypeScript on Windows 10 using node version 6.3.0 and npm version 3.10.3. The error message I'm getting is as follows: 33 warning Windows_NT 10.0.10586 34 warning argv "C:\\Program Files\&bs ...

How can you swap out a forward slash in vue.js?

I am facing a coding issue that I need help with: <template slot="popover"> <img :src="'img/articles/' + item.id + '_1.jpg'"> </template> Some of the numbers in my item.id contain slashes, leadin ...

Determine whether something has the potential to be a string in TypeScript

I am looking to create a TypeScript type that can identify whether an element has the potential to be a string. This means the element should have the type "string" or "any", but not "number", "boolean", "number[]", "Person", etc. I have experimented wit ...

The push action in NavController is not displaying Google Maps as expected

Trying to display a map upon clicking a button is proving challenging for me. It appears that the function NavController.push() does not work as expected, while NavController.setRoot() does. Despite not encountering any errors, I am unable to identify the ...

What's the deal with the `return of ()` syntax?

Just came across this piece of code: https://i.sstatic.net/JZXP5.png Code snippet in typescript. The first line looks like: ... return of (true); Can someone explain this syntax to me? ...

iPad with MDM restrictions will result in null values being returned for the window.navigator properties

Looking to identify whether a client is using an iPad, I am utilizing window.navigator.platform and window.navigator.maxTouchPoints. I'm implementing this logic in Vue by creating it as a computed property. One of the devices I have for testing is a ...

What are the best strategies for combining multiple TypeScript class decorators?

I have a set of unique class decorators that I apply to multiple classes. It looks something like this: @awesome @cool @amazing export class MySpecialClass { /* ..... */ } However, since I use these three decorators across many classes, I want to condens ...

The child route's vue-router named view is failing to function accurately

The nested route with a named router view is not loading correctly. When clicking the links in the navigation drawer, the corresponding content should be displayed in the v-content component. I have implemented this using named router views. Below are the ...

Problem encountered when trying to use the sharp package in NuxtJS

I attempted to implement this code in my Nuxt project, but it encountered an issue during compilation. Within my plugin/sharp.js file: import vue from "vue" import sharp from "sharp" vue.use(sharp) And in my nuxt.config.js file: plugi ...

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 ...

Tips for passing an id to a modal window component

I am currently working with Vue and Ionic, but I am unsure how to pass the lesson.id to the openModal() method. Here's the scenario: I have a card containing lesson data, including comments. When a user clicks on the comments, a modal window opens. I ...

Issue with Angular Compilation When Importing Library Function into Web Worker

I am facing an issue with a web worker in Angular that used to function properly in the previous versions: /// <reference lib="webworker" /> import { ParseResult } from "papaparse"; import { readCSV } from '@fireflysemantics/ ...

What is the method to incorporate type hints for my unique global Vue directives?

When I import or create a directive in an SFC file, I can receive TypeScript hints like this: import vFocus from 'my-custom-component-library'; View demo with ts hints However, if I globally register it in main.ts, the type hints are not availa ...

Using an array of references in React

I've encountered a problem where I'm trying to create a ref array from one component and then pass it to another inner component. However, simply passing them as props to the inner component doesn't work as it returns null. I attempted to fo ...

Optimal data structure for storage in a Next.js project with TypeScript

What is the appropriate data type for store in export let store: any; other than any? I have used @ts-igore to suppress TypeScript errors on the last line. How can I address the TypeScript error for that as well? I mentioned the boilerplates utilized in ...

Issue found in React Js test - TypeError: source.on does not exist as a function

I'm encountering an issue with my post request using multipart/form-data. Everything runs smoothly, except for the tests which are failing. When running the tests, I encounter an error message: TypeError: source.on is not a function. This is the code ...

Flexible type definition including omission and [key:string]: unknown

When I write code, I like to explain it afterwards: type ExampleType = { a: string; b: boolean; c: () => any; d?: boolean; e?: () => any; [inheritsProps: string]: unknown; // If this ^ line over is removed, TypeNoC would work as expecte ...

`How can I refresh the URL in Vue with new query parameters, even if it is the same page?`

I am facing an issue with my website that has a search bar. When a user searches and hits enter, I want the page to reload with the new query parameters in the URL. The challenge here is that if the user is already on the same page, although the query par ...

Creating a Robust Next.js Build with Tailor-Made Server (Nest.js)

I'm in need of assistance with compiling/building my project using Next.js while utilizing a custom server. Currently, I have integrated Nest.js (a TypeScript Node.js Framework) as the backend and nested Next.js within it. The integration seems to be ...

Does it seem typical to witness everything like this during the Vue JS CLI installation process?

Can anyone explain why I'm encountering numerous warnings and vulnerabilities after running the command npm install -g @vue/cli to globally install Vue JS 3 on a Windows system? Click here for a snapshot of the warnings ...