Vue.js and axios causing an empty array after the page is refreshed

As a newcomer to coding and using vue cli, along with my limited English skills, I apologize if I am unable to articulate the issue clearly. However, I am reaching out to the community for assistance.

The code snippet below is from store.js where I fetch JSON data from the server and aim to pass it to child components.

store.js

import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import VueAxios from "vue-axios";
import { library } from '@fortawesome/fontawesome-svg-core'
import { faCoffee } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'

library.add(faCoffee)

Vue.component('font-awesome-icon', FontAwesomeIcon)

Vue.use(Vuex);
Vue.use(VueAxios, axios);


export default new Vuex.Store({
  state: {
    beers: [],
    isLoaded: false
  },
  actions: {
    async loadCoins({ commit }) {
      axios
        .get("https://api.punkapi.com/v2/beers")
        .then(r => r.data)
        .then(beers => {
          commit("SET_BEERS", beers);
          commit("BEERS_LOADED", true);
        });
    }
  },
  mutations: {
    SET_BEERS(state, beers) {
      state.beers = beers;
    },
    BEERS_LOADED(state, isLoaded) {
      state.isLoaded = isLoaded;
    }
  },
});

In this file, home.vue component displays the data with a router link that should redirect me to the next component. The router link expects the item's id.

<template>
  <div>
    <div
      v-for="(value,index) in  beers"
      :key="index"
    >
      <router-link :to="{ path: `/about/${value.id}`}">
        <img
          class="logo lazy img-responsive loaded"
          v-bind:src="value.image_url"
        />
        <div>{{value.name}}</div>
        <div> {{value.tagline}}</div>
      </router-link>
    </div>
  </div>
</template>
    <script>
const _ = require("lodash");
import { mapState } from "vuex";
import Carousel from "@/components/carousel.vue";

export default {
  name: "home",
  components: {
    Carousel
  },
  data() {
    return {
      // filteredBeers: []
    };
  },
  mounted() {
    this.$store.dispatch("loadCoins");
    // this.test();
  },
  created() {},
  computed: {
    ...mapState(["beers", "isLoaded"]),
    consoleMyLog() {
      return this.isLoaded;
    }
  }
};
</script>

This file represents the page with details for each item. **The problem arises when I refresh the page as it displays an empty list**

I suspect that my approach might be incorrect but I lack understanding of why this happens and how to rectify it. It's possible I'm not utilizing the framework correctly.

Any recommendations or suggestions are greatly appreciated.

Thank you in advance

<template>
     <div>
          <img
            class=" logo" 
            v-bind:src="selectedArticle[0].image_url"
          />
          <h2 class="beer-title">
            {{selectedArticle[0].name}}
          </h2>
          <h3 class="beer-style">
            {{selectedArticle[0].contributed_by}}
          </h3>
     </div>
</template>


<script >
const _ = require("lodash");
import { mapState } from "vuex";

import Carousel from '@/components/carousel.vue'
export default {
  name: "about",
  props: {
    //  proId: this.$route.params.Pid,
  },
  components: {
    Carousel,
 
 },
  data() {
    return {
      

    };
  },
  computed: {
    // return the beers obj filter it by id and match it with route_id
    selectedArticle() {
      return this.$store.state.beers.filter(
        beer => beer.id == this.$route.params.id
      );
    }
  },
  mounted() {

   
  },
  }
</script>

Answer №1

It seems like the paths for home and about are separate routes.

Here is how the interaction unfolds:

  • The home component loads the data.
  • User navigates to about and the page renders correctly.
  • User refreshes the page, and now it's not functioning as expected.

If this scenario applies, the reason for the error becomes apparent. The home component loads the data in the mounted handler. Upon refreshing the page while on the about component, the action to load the data is no longer executed.

To address this issue, there are various solutions with different levels of effectiveness, simplicity, and scalability. However, based solely on the provided code snippet, the quickest fix would involve updating the mounted handler in about.vue:

mounted() {
  if (this.$store.state.beers.length === 0) this.$store.dispatch("loadCoins");
},

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 is the best approach to retrieve a username from a SQL database using AJAX within a Flask application

I have been attempting to retrieve the username column information from SQL using ajax, but only the username of the first ID is being returned. However, I need all usernames to be fetched. Below is the model: class users(db.Model): id=db.Column(db.I ...

``There seems to be an issue with the recognition of Vue.js, VSCode, Vetur, Emm

Currently utilizing Vue.js on VSCode with Vetur installed for formatting. Despite watching a video tutorial that mentioned Scaffold snippets and Emmett code completion should be available, I cannot seem to locate them on my VSCode. When attempting to typ ...

Toggle visibility of column data on button click in a Vue and Laravel application

I'm struggling with a table setup where each row contains a 'show details' button. Inside the table, there is another div stacked, and I want to display the table in the specific column when the button is clicked. However, I'm having di ...

Error encountered with the Schema in expressjs and mongoose frameworks

I am currently working on integrating mongoDB with an expressjs project using mongoose, and I have encountered a specific error. throw new mongoose.Error.MissingSchemaError(name); ^ MissingSchemaError: Schema hasn't been registered for model ...

How to override an event in JavaScript when a specific value is entered

I am looking to implement a system with complex conditions. The goal is to have an alert appear when a value is inputted and the button is clicked. First, a confirmation message Have you input ? should be displayed, followed by clicked with input. If no va ...

Creating an href link within a button that is contained within a collapse component

I am grappling with an issue where my collapsed model is displaying more information about clients; however, when I click on the button inside it, instead of getting the specific client's data, I end up retrieving information for all clients. <ion ...

How can I verify a user's role in Vuex?

I'm currently working on verifying the user role during login in Vue.js. Utilizing Vuex for state management, my goal is to redirect users with role = 1 (admin) to the admin panel and those with role = 0 (user) to the user dashboard. However, I seem t ...

jQuery does not have the capability to access the href attribute through DOM manipulation

I've been trying to extract the href attribute from a link in my code and create a new link using that attribute. However, I'm facing an issue where the created link doesn't seem to work properly - it keeps showing a 404 error message like t ...

One jQuery plugin was functioning perfectly, while the other one was failing to work as expected

I am working on a simple HTML file that includes a heading and two empty div elements. <h1>Blablabla.</h1> <div id="div1"></div> <div id="div2"></div> These two divs need to be populated with SVG content generated usin ...

Navigating in React: How to Implement the Same Route for Different Scenarios Without Compromising Your Application

I'm facing a frustrating issue while trying to incorporate Redux state management and React Router. Despite searching extensively online, I can't seem to find a solution. My Redux state, named user, stores the details of a logged-in user. Upon l ...

Identifying rectangular shapes in an image and overlaying a div on top using Jquery

I am currently exploring the possibility of achieving the following: Imagine having an image within a div (serving as the background image). This image resembles an Excel sheet. My goal is to generate an input tag or contenteditable div when a user clicks ...

After installing grunt, the Gruntfile cannot be located. How can this issue be resolved?

After installing grunt, I encountered a problem. Despite trying some commands suggested on stackoverflow in this How to install grunt and how to build script with it, running the grunt command still shows the same result. What steps should I take next?ht ...

Tips for sending an email without using MAILTO in JavaScript or jQuery

Today is a great day for many, but unfortunately not for me. I've been struggling with this issue for over two weeks now and can't seem to find a solution anywhere on the internet. Stack Overflow always comes to my rescue when things get really t ...

Angular request accessing CoinMarketCap API

Currently, I am immersing myself in the world of the latest CoinMarketCap API and navigating through the waters of data. The Node.js example below demonstrates how to make a request. But how can I achieve the same in Angular? Any tips or suggestions would ...

AngularJS does not allow empty spaces in textarea inputs

I am working on a form that includes a textarea element for users to input descriptions, however it does not allow any empty spaces. Users can only input alphanumeric and numeric characters, but no spaces. <textarea class="form-control" rows="4" maxl ...

Error TS2403: All variable declarations following the initial declaration must be of the same type in a React project

While developing my application using Reactjs, I encountered an error upon running it. The error message states: Subsequent variable declarations must have the same type. Variable 'WebGL2RenderingContext' must be of type '{ new (): WebGL2 ...

Need help tackling this issue: getting the error message "Route.post() is asking for a callback function, but received [object Undefined]

I am currently working on implementing a new contactUs page in my project that includes a form to store data in a mongoDB collection. However, after setting up all the controller and route files and launching the app, I encountered an error that I'm u ...

Information is only displayed within the Node Request function and is not accessible to

I am currently developing a small web scraping tool using Node (Express) to search URLs from a list. However, I'm encountering an issue with accessing the results of the search outside of the request callback function in a forEach loop. Can anyone hel ...

Authenticate with Google using the Javascript API without causing a pop-up to appear

Here is the code I'm using to allow users to log in with their Google account via the Javascript API. HTML <a id="gp_login" href="javascript:void(0)" onclick="javascript:googleAuth()">Login using Google</a> Javascript function gPOnLoad ...

Utilizing React Native Camera Kit allows for the seamless and continuous scanning of QR codes, offering multiple callbacks when a code is

Attempting to integrate a QR code scanner into my project using react native. Utilizing the plugin react-native-camera-kit, which supports both QR and Bar code scanning. However, I am facing an issue where the scanner continuously scans the code and trig ...