When I navigate to the URL using a router-link, the v-for in my Vue.js component renders properly. However, if I manually type the URL or refresh the page, the v-for fails to render

Whenever I navigate to a specific URL that showcases icons of characters from a game, everything functions as expected and the icons are displayed. However, upon refreshing the page, the icons vanish.

If I manually enter www.example.com/champions, the icons do not render at all. Why is this occurring?

This is my component:

<template>
    <div class='wrapper'>
        <div class="champions-container">
            <div v-for='champion in champions' class="champion">
                <img class='responsive-image' :src="'http://ddragon.leagueoflegends.com/cdn/' + $store.getters.version + '/img/champion/' + champion.image.full" alt="">
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data(){
            return {
                champions: this.$store.state.fullChampions
            }
        }
    }
</script>

And here's my Vuex store where the champions are stored:

export default new Vuex.Store({
    state: {
        version: null,
        fullChampions: null
    },
    mutations: {
        version(state, data){
            state.version = data.version
        },
        fullChampions(state, data){
            state.fullChampions = data.fullChampions
        }
    },
    actions: {
        getVersion({commit}){
            return axios.get("http://ddragon.leagueoflegends.com/api/versions.json")
            .then((response) => {
                commit('version', {
                    version: response.data[0]
                })
            })
            .catch(function (error) {
                console.log(error);
            })
        },
        getFullChampions({commit, state}){
            return axios.get("https://ddragon.leagueoflegends.com/cdn/" + state.version + "/data/en_US/championFull.json")
            .then((response) => {
                commit('fullChampions', {
                    fullChampions: Object.values(response.data.data)
                })
            })
            .catch(function (error) {
                console.log(error);
            })
        },

Answer №1

It appears that the issues you are facing may be related to the following reasons.

First: The component responsible for dispatching your getFullChampions function in vuex may not be the one you are currently looking at.

Second: You seem to be assigning a value to champions without updating the state of fullChampions.

this.champions: this.$store.state.fullChampions // state.fullChampions might not have been updated yet.

You can try the following solution.

watch: {
      '$store.state.fullChampions': function() {
           this.champions = this.$store.state.fullChampions  
      },
}

Last but not least: Make sure to add a condition above your v-for loop to prevent any errors from occurring.

<div class="champions-container" v-if=""$store.getters.version>
    <div v-for='champion in champions' class="champion">
        <img class='responsive-image' :src="'http://ddragon.leagueoflegends.com/cdn/' + $store.getters.version + '/img/champion/' + champion.image.full" alt="">
    </div>
</div>

Answer №2

Could you please consider incorporating the following code snippet:

watch: {
    $route: function(val, OldVal){
        this.champions = this.$store.state.fullChampions;
    }
},

right after your data section?

Update:

If you are executing the getFullChampions() action, you may want to trigger it within the watcher of my example instead of directly assigning it to this.champions.

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

Ensure that the input remains below ten

My goal here is to ensure that the value in an input element is a non-zero digit (0<x<=9). Here's the HTML tag I'm using: <input type="number" class="cell"> I've experimented with various JavaScript solutions, but so far none h ...

What is the best way to implement promise function in a JavaScript functional method such as forEach or reduce?

I have implemented a promise function in the following way: // WORK let res = {approveList: [], rejectList: [], errorId: rv.errorId, errorDesc: rv.errorDesc}; for (let i = 0; i < rv.copyDetailList.length; i ++) { const item = rv.copyDetailList[i]; ...

What is the process for incorporating a glossiness / specular texture onto a GLTF model?

QUERY: I currently possess a specular/glossiness texture image for a model that has not yet been integrated into the GLTF model. Is there a way to incorporate/add this texture to my model in order to achieve a reflective/glossy appearance where required? ...

Error: Unable to access the 'Result' property because it is undefined

I am encountering an issue while attempting to showcase database results, and the error message I'm receiving is: TypeError: Cannot read property 'Result' of undefined I am in the process of developing a Single Page Application with Angula ...

Creating interactive network visualizations using JavaScript

I've been in search of javascript code that can help me create a visual representation similar to this example. Specifically, I need something that can display links between boxes when clicked on or hovered over. I'm still not sure what this par ...

The reason why JavaScript condenses two or more spaces into just one space

After encountering a problem with my HTML/JS/Angular script, I created a simple demo to illustrate the issue. Although I have found a solution, I still wanted to seek advice from experts. <body ng-app> <div ng-controller='abc'> ...

Exploring alternative applications of defineModel in Vue 3.4 beyond just handling inputs

The examples provided for defineModel in the Vue documentation primarily focus on data inputs. I was curious if this functionality could be utilized in different contexts, potentially eliminating the need for the somewhat cumbersome props/emit approach to ...

Incorporating a delay into looped HTTP requests while effectively utilizing Promise.all to track their completion

Greetings! In my current project, I am trying to introduce a 50ms delay before each subsequent HTTP request is sent to the server. Additionally, I aim to incorporate a functionality that triggers after all requests have been successfully made. To better e ...

Display/Conceal WP Submenu

Struggling to switch the behavior of my Wordpress menu. Want it to display when clicked, not when hovered: <nav> <ul> <li> <?php wp_nav_menu( array( 'theme_location' => 'header-menu' ) ); ...

In Firefox, there is a peculiar issue where one of the text boxes in an HTML form does not display

In my HTML form, users can input their first name, last name, and phone number to create an account ID. The textboxes for first name, last name, and account ID work smoothly on all browsers except Firefox. Surprisingly, the phone number textbox doesn' ...

Pass data from a Firebase JavaScript callback function in the Data Access Layer (DAL) to another function in the controller

I have been developing a basic chat application that enables users to send messages in a group chat and see them instantly updated. To achieve this, I opted for Firebase and spent time familiarizing myself with its web API. However, I encountered difficult ...

Passport Node: Issue with Password Comparison results in an undefined function error, causing return done(null, user) to fail

I have reviewed all the relevant inquiries and responses but I am still unable to resolve this issue. Please see the code provided below and assist me in understanding why the terminal is displaying 'undefined is not a function'. Here is an overv ...

What is the best way to delay the rendering of my Vue component until a function call is finished?

After extensive research online, I have been unable to discover a specific solution to my issue. The problem is that I have a Vue component that relies on an init call and I need it to avoid rendering until the call is successfully completed. Once the ca ...

"Clicking on a jQuery div will cause it to slide down, and clicking again

I am currently working on this code snippet: $("#right").click(function() { $("#signin").stop().slideDown(300); }); At the moment, it drops down when clicked, but I would like it to slideUp() when clicked again. Your help is appreciated. On a relate ...

What could be causing my Leaflet popup to suddenly close?

My feature allows users to search for a marker and zoom to its location, triggering the popup to open. Everything is functioning correctly, except that the popup closes after the function executes. I am struggling to pinpoint what is causing the popup to c ...

Font modification is unsuccessful in Vue-Material

Here is a snippet from my App.vue file where I encountered an issue with changing the font in the md-tabs component, taken from . The CSS line: background: #42A5F5; works perfectly fine, but this one does not: color: #E3F2FD; App.vue: <template> ...

Modify the border in jQuery if a specific div exists within a list item

Here is a collection of items: <div class="wine"> <H1>Title</H1> <div class="promotion"></div></div> <div class="wine"> <H1>Title</H1> </div></div> <div class="wine"> <H1>Title& ...

Elasticsearch query fails to execute when encountering a special character not properly escaped

I am facing an issue with querying a keyword that includes a dot (.) at the end. While the query works perfectly on Kibana's console, it fails to execute on my application's function. The following function is responsible for creating the query b ...

Troubleshooting Vue Computed Property Doesn't Refresh

I am experiencing an issue with a computed function that I want to use. Every time I attempt to remove the forward slashes and 'SYG' at the end of the string "99/KRFS/010572//SYG" pasted into a v-model input, I receive the error message "Computed ...

Implementing role-based authentication in Next.js using Next-auth and Firebase

Currently, I'm in the process of integrating role-based authentication using NextAuth.js into my Next.js application. Despite following the provided documentation meticulously, an error (in profile snippet and callback snippet which I copied from next ...