Refreshing the page in VueJs does not trigger the axios function

I've encountered an issue with my VueJs app after purchasing the Vuexy template from ThemeForest. I created a new component called CountryTable.vue, and while it works initially, it fails to display data when I refresh the page. It only shows data when I login or navigate to another page. Here is the structure of my CountryTable component:

<template>
<div class="vx-col w-full">
<vx-card title="Countries">
<div slot="no-body" class="mt-4">

  <vs-table class="table-dark-inverted" :data="activeCountries">
    <template slot="thead">
      <vs-th sort-key="name" colspan="2">Country</vs-th>
      <vs-th sort-key="sales">Sales</vs-th>
      <vs-th sort-key="products">Products</vs-th>
      <vs-th sort-key="accessories">Accessories</vs-th>
      <vs-th sort-key="basket">Basket</vs-th>
      <vs-th sort-key="deliveries">Deliveries</vs-th>
      <vs-th sort-key="amount">Amount</vs-th>
    </template>

    <template slot-scope="{data}" class="text-center">
      <vs-tr :data="tr" :key="indextr" v-for="(tr, indextr) in data" :style="{animation: 'flipInX ' +  (indextr * 0.2) + 's'}">

        <vs-td :data="data[indextr].name">
        <img width="30" :src="data[indextr].flag" :alt="data[indextr].name">
        </vs-td>

        <vs-td :data="data[indextr].name">
          {{ data[indextr].name }}
        </vs-td>

        <vs-td :data="data[indextr].sales">
          {{ data[indextr].sales }}
        </vs-td>

        <vs-td :data="data[indextr].products">
          {{ data[indextr].products }}
        </vs-td>

        <vs-td :data="data[indextr].accessories">
          {{ data[indextr].accessories }}
        </vs-td>
        
        <vs-td :data="data[indextr].basket">
          {{ data[indextr].basket }}
        </vs-td>

        <vs-td :data="data[indextr].deliveries">
          {{ data[indextr].deliveries }}
        </vs-td>

        <vs-td :data="data[indextr].amount">
          {{ data[indextr].amount }}
        </vs-td>

      </vs-tr>
    </template>
    </vs-table>
</div>
    </vx-card>
    
    </div>
</template>

<script>
import { mapState } from "vuex";
import Countries from "../../http/Countries";

export default {
  data() {
    return {
      selected: [],
      'tableList': [
        'vs-th: Component',
        'vs-tr: Component',
        'vs-td: Component',
        'thread: Slot',
        'tbody: Slot',
        'header: Slot'
      ]
    }
  },
  computed: {
            ...mapState({
              activeCountries: state => state.activeCountries
            })
        },

  mounted() {
      Countries.activeCountries().then(response => {
        this.$store.commit("ACTIVE_COUNTRIES", response.data.countries);
      });
  }
}

</script>

Here's how the Countries file method looks like:

activeCountries() {
    return Api().get("/userCountries");
  },

And this is the API setup:

import axios from "axios";

let BaseApi = axios.create({
  baseURL: "http://127.0.0.1:8000/api/"
});

let Api = function() {
  let token = localStorage.getItem("accessToken");

  if (token) {
    BaseApi.defaults.headers.common["Authorization"] = `Bearer ${token}`;
  }

  return BaseApi;
};

export default Api;

The console error message indicates:

TypeError: Invalid attempt to spread non-iterable instance

It seems that the table rendering and API integration are causing issues. Could the 'mounted' function be the culprit? I've tried using 'created' and 'updated' without success.

Answer №1

Seems like the issue lies with the mapState function.

You can resolve it by updating from:

...mapState({
    activeCountries: state => state.activeCountries
})

to:

...mapState(['activeCountries'])

Answer №2

After attempting to update certain dependencies, I encountered numerous errors when running the application. Fortunately, reinstalling the same dependencies resolved the issue and now everything is functioning properly.

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

Tips for obtaining user input to place markers on a video timeline with JavaScript

I am new to Java script and I am trying to create a video player where users can click on the progress bar to place markers. Can you please review my code below and let me know if there are any errors? index.html <!doctype html> <html> <he ...

Refreshing a data object that is shared among Vue components

I've recently started diving into Vue, and I've found myself responsible for tweaking an existing codebase. There's this data.js file that caught my attention, containing a handful of objects holding city information, like: export default { ...

By leveraging the require module, programmatically load the content of a JSON file in Node.js and Mocha by passing

Utilizing mocha, node js, and the cypress tool for writing test scripts has been successful in loading data from a json file with the following statement: var data = require('../../fixtures/TestData/JsonData/ABC_DEF.json'); However, attempting ...

Controlling the angular bootstrap modal form with ease

I am having trouble accessing the form in the modal controller (Plunkr). The variable myForm doesn't seem to be accessible. How can I make the alert call work correctly: angular.module('plunker', ['ui.bootstrap']); var ModalDemoCt ...

Firefox not responding to mouse movements

I am experimenting with creating an "animation" using JavaScript's "mousemove" Check it out here This is the code I am currently using $("body").mousemove(function(e){ var wWidth = $("body").width()/2 var wHeight = $("body").height()/2 var posX; v ...

The express post request body fails to appear, rendering it empty

Server Side Code const express = require('express'); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended:true })); app.post('/',(req,res)=>{ console.log(req.body) }) Client Side Code const da ...

How to clear input fields in Ant Design ReactJS components

Utilizing the form list component from antd in my react.js project https://ant.design/components/form/#Form.List I have a basic form list set up where I can easily add or remove fields. At times, I need to reset the form and remove any additional items t ...

Error encountered in vue.js due to a ReferenceError when the resize event is used

I'm having trouble obtaining the window height when resizing, and I keep encountering the error ReferenceError: calcOfSliderHeight is not defined. Can someone explain what's happening? Here is my code: let example = new Vue({ el: '#exam ...

What is the best way to choose the current Div's ID, as well as its Width and Height properties?

Within this section, there are four div elements with varying widths, heights, and colors that appear and disappear when their respective buttons are clicked. I am adding an "activeDiv" class to the visible div in order to easily select it using that class ...

Employing jq to transfer the value of a child property to the parent dictionary

My TopoJSON file contains multiple geometries, structured as follows: { "type": "Topology", "objects": { "delegaciones": { "geometries": [ { "properties": { "name": "Tlalpan", "municip": "012", ...

Having trouble getting NPM environment variables to function properly on a Windows system?

I have a confusion in my package.json file where I am attempting to compile less code using versioning. Here is an example of what I am trying to achieve: "scripts" { ... "build:css": "lessc --source-map css/index.less build/$npm_package_name.$npm_package ...

The URL for the Javascript chunk includes colons at https://example.com/js/chunk-vendors.b3792e11.js:18:16400

I recently completed a Vue application and used npm run build to generate the files. Upon uploading the dist folder to my Apache server, I encountered an issue where Apache was unable to locate the file when trying to access a specific part of the app (:18 ...

Fill in datatable with information from a JSON array if there are missing values in certain columns

My goal is to populate a datatable in JavaScript. Currently, I am able to do so, but some of the last rows have blank columns which are populated first. I attempted to fill those blank columns, and then the data populates in order. Here is an example of my ...

Named functions in Typescript within functional components are the best practice for improving

How can I implement handleFoo using MyType['foo']? type MyType { foo: () => void } const Comp: React.FunctionComponent<{}> = () => { function handleFoo() {} return ... } I'm looking for a solution that doesn't inv ...

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...

Node.js: App crashed, standing by for file changes to initiate restart

While I was in the middle of a nodejs course on Udemy, I encountered an issue where the code suddenly started breaking and throwing errors. Even after attempting to replicate the instructor's code, the problem persisted. I sought guidance from this a ...

Angular.js: The $setDirty() method on a form does not automatically affect its child form elements

Currently, I am working on a form validation project using Angular.js. A specific challenge that I am facing is setting the dirty state on a child element of a form in an isolated scope within a directive. Does anyone know how to achieve this and set the i ...

Troubleshooting: Issues with AngularJS $route.reload() functionality

I have an angular app and I'm attempting to refresh the page. I've tried using $route.reload() as recommended in multiple posts, but I can't seem to get it to work (Chrome is showing me an error). Here's my controller: var app = angula ...

leveraging express.js middleware alongside jwt and express-jwt for secured authentication in express framework

I am encountering an issue while using the express-jwt to create a custom middleware. The error message persists as follows: app.use(expressJwt({ secret: SECRET, algorithms: ['HS256']}).unless({path: ['/login', '/']})); ...

How can I maintain focus selection while replacing HTML with text in a contenteditable div without losing it?

When working with a div tag that needs to be editable, the goal is to prevent users from entering any HTML into the tag. However, despite efforts to restrict input, when users copy and paste content, it often includes unwanted tags. To address this issue, ...