Why isn't my Vue.js3 table being updated after using axios asynchronously?

After conducting my research, it appears that I have followed all the correct steps. However, I am unable to identify why my table is not updating.

Initially, I create a new company and proceed to the overview, but nothing is being displayed. While checking the logs, I can see all the companies that have been created, yet none of them are rendering.

In the web browser console, I can see data being logged from the restapi-companies.

When fetching these companies, everything seems to be working fine.

Do I need to trigger a specific event or is there an underlying issue that needs to be addressed?

Below is the full development code:

  1. restapi-companies.ts:
export type CompanyPojo = {
  id: number;
  name: string;
  legalForm: string;
  additionalName: string;
};

export type CompanyPojoResponse = {
  data: CompanyPojo[];
};

import axios from "axios";

export async function findAllCompanies() {
  try {
    const { data, status } = await axios.get<CompanyPojoResponse>(
      "http://localhost:9050/api/v1/company/all",
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: "Basic YWRtaW46YWRtaW5QYXNz",
        },
      }
    );

    console.log(JSON.stringify(data, null, 4));

    // ?? "response status is: 200"
    console.log("response status is: ", status);

    return data;
  } catch (error) {
    if (axios.isAxiosError(error)) {
      console.log("error message: ", error.message);
      console.log("error message: ", error);
    } else {
      console.log("unexpected error: ", error);
    }
  }

  return <CompanyPojoResponse>{};
}
  1. Vue-Template
<script>
import { findAllCompanies } from "@/rest/restapi-companies"
import { ref } from "vue"

export default {
  data() {
    return {
      companies: ref([])
    }
  },
  mounted() {
    findAllCompanies().then((response) => {
      this.companies = response.data
    })
  }
}
</script>

<template>
  <div class="top-nav">
    <nav>
      <RouterLink to="/new-company">New Company</RouterLink>
      <!-- view product list -->
      <!-- create new product -->
    </nav>
  </div>

  <table id="companyTable">
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Additional Name</th>
        <th>Legal Form</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="company in companies">
        <td>{{ company.id }}</td>
        <td>{{ company.name }}</td>
        <td>{{ company.additionalName }}</td>
        <td>{{ company.legalForm }}</td>
      </tr>
    </tbody>
  </table>
</template>

Answer №1

You are extracting the data from the response twice: once within the findAllCompanies function (by destructuring data) and once in the mounted() hook (response.data).

  // ...
  mounted() {
    findAllCompanies().then((data) => {
      this.companies = data
    })
  }

...this should resolve the issue.


On a side note: data is already reactive, so there is no need to make it reactive (thus ref([]) is unnecessary).

export default {
  data: () => ({ companies: [] }),
  //...
}

...this should suffice.


Since you are using Vue3 and Typescript, it is recommended to structure your component as:

<script setup lang="ts">
import { findAllCompanies, CompanyPojo } from "@/rest/restapi-companies"
import { ref, onMounted } from "vue"

const companies = ref<CompanyPojo[]>([])
onMounted(async () => {
  companies.value = await findAllCompanies()
})
</script>

Additionally, it might be better to return an empty array (not an empty object) in the error branch.

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

Trouble with Vuetify autocomplete not showing loading indicator

My issue revolves around an autocomplete field that loads data from the backend. Below is a simplified version of the code: <div class="form-row"> <v-autocomplete :solo="true" v-model="user.place.value" :ite ...

A TypeScript class that is a concrete implementation of a generic type

When handling a login operation, I receive an HTTP response like this: interface ILoginResponse { // ok message: string token: string; } This response structure is part of a generic response format that I intend to use for all my HTTP responses: i ...

Synchronizing Vuetify Carousel with dynamic route parameters

I'm facing an issue where the v-carousel value does not sync correctly with a route parameter using a computed property. Despite waiting for the mounted hook, the carousel seems to emit its own input and disregard the initial value from the route para ...

Typescript's tree-pruning strategy design for optimization

I've been working on developing a library that enforces the use of specific strategies for each target. The current structure I have in place is as follows: [Application] -> contains -> [player] -> contains -> [renderer] In the current s ...

This phrase cannot be invoked

My code seems correct for functionality, but I am encountering an error in my component that I do not know how to resolve. Can someone please help me with this issue? This expression is not callable. Not all constituents of type 'string | ((sectionNa ...

Eliminate the usage of JSON.stringify in the Reducer function

I have a system where I store chat messages in a dictionary with the date as the key and a list of messages as the value. Whenever a new message is added, the following code snippet is executed. Is there a way to enhance the existing code to eliminate the ...

Angular: accomplish cascading requests to achieve desired outcomes

While exploring Angular rxjs operators, I came across a scenario where I need to send requests to the server that depend on each other. Currently, I have a modal window open and during the ngOnInit lifecycle hook, multiple requests are being sent, some of ...

Unfortunately, my deployment on Vercel encountered an error related to npm. Specifically, the error involved the extraction of a file from the tarball for node-v18.15

Trying to deploy my GitHub project on Vercel. The project is built using Vue. However, when building the project on Vercel, I encountered numerous errors like this: npm ERR! gyp verb extracted file from tarball node-v18.15.0/include/node/openssl/archs/VC-W ...

Aliases for NPM packages and TypeScript declaration files

I am in need of two separate versions of a package, and fortunately with npm 6.9.0 I can easily accomplish that now. My dilemma is this: the package comes with type definitions. However, when I create an alias for this package and refer to it using the al ...

What is the best way to define types for an array of objects with interconnected properties?

I need to define a type for an object called root, which holds a nested array of objects called values. Each object in the array has properties named one (of any type) and all (an array of the same type as one). Below is my attempt at creating this type d ...

Access cookie information within a Vue application by reading it within the router or component

There is a url (*/webapp/callback) in my vue.js app that gets redirected (http 302) from another application, bringing along some cookies. I'm trying to figure out how I can read these cookies when the component mounts and then store them in vuex stat ...

Vueify is unable to import a component from the node_modules directory

Check out my latest npm package Step one, I begin by installing it. npm install asva-vue-filters Next, I include the package in my javascript file: var vueFilters = require('asva-vue-filters') However, I encounter a barrage of errors like th ...

Having trouble creating a scatter chart using vue-charts library

Whenever I try to render the chart, all I get is a blank page along with this error message: TypeError: Cannot read property 'getBasePixel' of undefined There seems to be an issue with my implementation in Vue.js even though I followed the ex ...

The functionality of TypeScript's .entries() method is not available for the type 'DOMTokenList'

I'm currently working with a stack that includes Vue3, Vite, and TypeScript. I've encountered an issue related to DOMTokenList where I'm trying to utilize the .entries() method but TypeScript throws an error saying Property 'entries&apo ...

Update of Angular Material Table rows triggers a popup, however only the values from the first array are populated in all edited rows

Developed an application with two components (A & B) that includes a popup dialog for editing: Component A fetches the data from a service and loads it into a data table Component B initializes the data when a pop event is triggered from A. Usually, ...

When handling a document click event in Typescript, an error may occur where it cannot read

Just starting out with Typescript and diving into Angular, I am currently in the process of converting my project to the Angular system. However, I've hit a roadblock. I need to figure out how to close the dropdown content when the user clicks anywher ...

Connecting data with Angular

Recently, as part of my learning journey with Angular, I encountered an intriguing issue. While working on my code, I noticed that the error popped up in my code editor (VSCode) but not when running the code in the browser. The dilemma stemmed from settin ...

Property '{}' is not defined in type - Angular version 9.1.1

Currently, I am working with Angular CLI version 9.1.1 and I am attempting to update certain data without updating all of it. form: UserInfo = {adresse : {}}; UserInfo.interface export interface UserInfo { id_user: string; username: string; em ...

Ways to compel string type or disregard type?

When using the following code snippet: <Image src={user?.profilePictureUrl} alt={user?.name} /> An error is encountered: Type 'string | null | undefined' is not assignable to type 'string | StaticImport'. Type 'undefined ...

Tips on updating the datepicker format to be dd/mm/yyyy in ngbdatepicker

I am currently using ng-bootstrap for a datepicker and need to change the date format from yyyy/mm/dd to dd/mm/yyyy. I have tried to make this adjustment but haven't had success. If anyone has suggestions on how to accomplish this, please help. Here ...