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

Optimal Strategies for Handling CSRF Tokens with AJAX Requests in Laravel 9 and Beyond

When working with Laravel 9+, it is crucial to expose CSRF tokens for AJAX requests in order to maintain security measures. However, the placement of these tokens can impact code organization and elegance. There are two main approaches: Approach 1: Direct ...

Modify how the browser typically processes script tags as its default behavior

Most of us are familiar with the functionality of <script src="/something.js"></script>. This loads the specified file onto the page and executes the script contained within. Is there a way to modify how <script> elements are interpreted ...

Webstorm encounters difficulties compiling Sass

While attempting to utilize Sass in the Webstorm IDE, I noticed that it is defaulting to Ruby 1.8 (OS Default) instead of my preferred RVM Ruby Version (1.9.x). To address this issue, I tried setting the path for Sass in the Watcher-Configuration: PATH=$ ...

AngularJS offers a single checkbox that allows users to select or

For my code, I need to implement a single checkbox. In my doc.ejs file: <tr ng-repeat="folder_l in folderlist | orderBy:created_date" > <td> <div class="permit"> <input class="chkbtn move_check" type="checkbox" id=" ...

Accessing method from child component in parent component in Vue.js is a common requirement that can be easily

Is there a way to access a method in the parent component from the child component? I attempted to use mixins but found that the function was returning null instead of the expected value. However, when emitting an object, it worked fine in the parent compo ...

The issue of javascript Map not updating its state is causing a problem

I've encountered an issue where my components are not re-rendering with the updated state when using a map to store state. const storage = (set, get) => ({ items: new Map(), addItem: (key, item) => { set((state) => state.items ...

Choose to either check or uncheck boxes using ReactJS

After successfully creating a function to select either single or multiple boxes, I encountered an issue with the "Select all" feature. Any suggestions on how to resolve this? (I'm utilizing the material-ui library for my checkboxes, which are essenti ...

Struggling with the integration of a custom login feature using next-auth, leading to being constantly redirected to api/auth/error

Currently, I am facing a challenge while working on my Next.js application. The issue lies with the authentication process which is managed by a separate Node.js API deployed on Heroku. My objective is to utilize NextAuth.js for user session management in ...

Easy Steps to Simplify Your Code for Variable Management

I currently have 6 tabs, each with their own object. Data is being received from the server and filtered based on the tab name. var a = {} // First Tab Object var b = {} // Second Tab Object var c = {} // Third Tab Object var d = {}// Fou ...

What could be the reason that the painting application is not functioning properly on mobile devices?

I am facing an issue with my painting app where it works perfectly on desktop browsers but fails to function on mobile devices. I tried adding event listeners for mobile events, which are understood by mobile devices, but unfortunately, that did not solve ...

How can I prevent scrolling in a Vue mobile menu?

In this scenario, the toggle for the menu is controlled by a checkbox with the id "check" below. I attempted to bind v-bind:class="[{'antiscroll': checkboxValue}]" to the body in HTML, and also in the main App.vue file, but it did not work as exp ...

Guide on validating an email through a 6-digit code using Flutter, Node.js, and MongoDB

My goal is to create a registration process where users enter their email and password on a screen. After clicking "register", they should receive an email with a random 6-digit code for verification on the next page. I have everything set up, but I' ...

What is the best way to implement dynamic generation of Form::date() in Laravel 8?

Is there a way to dynamically generate the Form::date() based on the selection of 1? If 1 is selected, then display the Form::date() under the Form::select(). However, if 0 is selected, then hide the Form::date() in this particular view. For example: Sel ...

Listening to changes in a URL using JQuery

Is there a way to detect when the browser URL has been modified? I am facing the following situation: On my webpage, I have an iframe that changes its content and updates the browser's URL through JavaScript when a user interacts with it. However, no ...

Utilizing mustache template strings within the href attribute in VueJS

How can I incorporate a mustache inside an href attribute within the context of Vue.js? After researching various solutions, I attempted to apply them to my code. Mustache inside an href How to pass a value from Vue data to an href? Reddit thread on us ...

Searching for a specific match in JSON data using React streaming technology: encountering issues with the .find method as

Having experience with functional programming in Java, I recently ventured into JavaScript. My current task involves streaming through a JSON output structured like this: { "originatingRequest": { "clientId": 1, "simulationName": "Sea ...

Issue encountered while trying to define a global variable within a JavaScript Class

I'm currently working on setting up a page variable that can be utilized by my Scroller class for implementing infinite scrolling. It's crucial for this variable to have global scope, as it needs to retain its value outside of the ajax function. ...

An error occurs in TypeScript when attempting to reduce a loop on an array

My array consists of objects structured like this type AnyType = { name: 'A' | 'B' | 'C'; isAny:boolean; }; const myArray :AnyType[] =[ {name:'A',isAny:true}, {name:'B',isAny:false}, ] I am trying ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...

Material UI Input Field, Present Cursor Location

Is there a way to retrieve the current cursor (caret) position in a MaterialUI text field? https://material-ui.com/components/text-fields/ I am looking to make changes to the string content at a specific index, such as inserting a character X between cha ...