In Vue.js, both components receive props from App.js, however, one of the components ends up losing the prop

There are times when I am on the "ActorDetails.vue" page/component, and after refreshing my browser a few times, I notice that the data in my actorsData prop (which should contain an array of 5 objects) becomes an empty array. Initially, I thought it was an issue with the API, but upon logging the data inside "App.js," I found that the data does exist. I'm struggling to pinpoint where the problem lies. Interestingly, when I refresh the browser on the "ActorsList.vue" page/component, the prop data always remains intact.

It's worth noting that both pages/components ("ActorList.vue" and "ActorDetails.vue") retrieve the topActors data from "App.vue."

(Code comments included)

App.vue

<template>
  <div id="app">
    <router-view name="homePage" />
    <router-view :actorsData="topActors" /> <== Both "ActorList.vue" and "ActorDetails.vue" utilize this "router-view"
    <div class="over-limit-resolution">Over 4k</div>
  </div>
</template>

<script>
import { getActors } from "./util/TheMoveDatabase";
export default {
  name: "App",
  data() {
    return {
      topActors: [],
    };
  },
  created() {
    getActors.then((result) => {
      console.log(result); <== The data consistently returns from the API even when the "actorsData" prop within "ActorsDetails.vue" loses its data.
      this.topActors = result;
    });
  },
  methods: {},
};
</script>

ActorsList.vue

<template>
  <div class="actors-list">
    <router-link to="/">Home</router-link>

    <div class="actors-list-container" v-if="allFiveActors">
      <div
        class="actor-container"
        v-for="actorData in actorsData"
        :key="actorData.id"
      >
        <router-link :to="'/actorslist/' + actorData.id">
          <h3>{{ actorData.name }} | {{ actorData.id }}</h3>
        </router-link>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "ActorsList",
  props: ["actorsData"],
  data() {
    return {};
  },
  computed: {
    allFiveActors() {
      return this.actorsData.length > 0;
    },
  },
  created() {
    console.log(this.actorsData); <== Even after trying to refresh the browser while on this page/component, the prop data consistently persists.
  },
};

ActorsDetails.vue (Page/Component experiencing prop data loss)

<template>
  <div class="actor-details">
    <router-link to="/actorslist">Actors List</router-link>
    <h1>Details page</h1>
    <div class="actor-details-container" v-if="actorDetails">
      <div class="actor-detail-info">
        <h3>{{ actorDetails.name }}</h3>
        <p>Birthday: {{ actorDetails.birthday }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import { getActorDetails } from "../util/TheMoveDatabase";
export default {
  name: "ActorDetails",
  props: ["actorsData", "actorId"],
  data() {
    return {
      actorDetails: {},
    };
  },
  methods: {
    checkCurrentActorExist() {
      const currentActor = this.getCurrentActor;
      // console.log(currentActor);
      if (!currentActor) {
        // this.$router.push("/");
        console.log("does not exist");
      }
    },

    getActor() {
      const currentActor = this.getCurrentActor;
      console.log(currentActor);
      console.log("RAN");

      if (currentActor) {
        getActorDetails(this.actorId).then((result) => {
          this.actorDetails = result;
          console.log(this.actorDetails);
        });
      }
    },
  },

  created() {
    this.checkCurrentActorExist();
    this.getActor();
    console.log(this.actorsData); <== When I'm on this page/component and refresh the browser multiple times, sometimes my "actorsData" prop data disappears.
    console.log(this.actorId);
  },

  computed: {
    getCurrentActor() {
      return this.actorsData.find(
        (actor) => actor.id === parseInt(this.actorId)
      );
    },
  },
};
</script>

Routes.js

import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';

Vue.use(VueRouter);

const routes = [
    {
        path: '/',
        name: 'Home',
        components: {
            homePage: Home,
        },
    },
    {
        path: '/actorslist',
        name: 'ActorsList',
        component: () => import('../views/ActorsList.vue'),
    },
    {
        path: '/actorslist/:actorId',
        name: 'ActorDetails',
        component: () => import('../views/ActorDetails.vue'),
        props(route) {
            // console.log(route);
            return {
                actorId: route.params.actorId,
            };
        },
    },
];

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes,
});

export default router;

Answer №1

Perhaps it is possible that the loading process is occasionally slow, causing the empty array to be passed to the component prematurely. To address this issue, consider clearing the array and reloading it with the data once it has been fully loaded instead of creating a new array altogether. You could try using methods like splice or pop to clear the array before refilling it with push.

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

Executing the default function for a successful response when using Jquery's $.post

Is there a way to automatically execute specific functions after every successful completion of a $.post request? For example, currently I have the following code: $.post(ROOT + 'Ajax', { call: 'Enquiry->setEnquiryUrgency', ...

disable comment section in angular and update display

Is there a way to revert back to the original view after clicking on the edit button when the view is changed using ng-if? I want to go back by clicking the cancel button. <div class="timeline-body"> <div marked="cmnt.conten ...

Adding data from one object to another in Javascript results in duplicated entries

Despite my efforts to find a solution for my issue, I couldn't locate a relevant topic. Being new to Javascript, I suspect my lack of understanding is hindering me from resolving the problem. After days of trying, I'm still unable to grasp it. An ...

Trouble with passing options to ES6 module imports

After coming across this Stackoverflow thread, I am attempting to pass options to ES6 imports. Initially, this code worked without any issues: export default (Param1:any, Param2:any) => { return class Foo { constructor() { cons ...

Exploring the seamless integration of okta-vue within VueCLI4

Currently, I am in the process of setting up a Vue authentication page using the Okta-Vue package. The tutorial that I am following can be found here: . For this particular project, I have opted to use VueCLI 4. Following the creation of the project, my ne ...

Submitting a POST request to a Node.js Server is causing a prolonged loading time, leading to an error message of

Struggling with a simple form that sends user input to the server and encountering ERR_EMPTY_RESPONSE after submission? Don't worry, I can successfully log the input from the form using console.log, confirming that it is reaching the server. Here is ...

Sending the id as a prop in react-router-dom

Is it possible to pass an ID in props to a React component using react-router-dom? Take a look at my app.js file below: <Switch location={this.props.location}> <Route exact path="/" component={Home} /> <Route path= ...

What steps can be taken to troubleshoot the 'unimplemented or irrational conversion requested' error?

I am facing an issue with passing a substantial amount of records as a stringify object from the client to the server. On the server side, there is a function named 'Get_Records' that is supposed to receive and process this string object by parsi ...

Vue 3's defineExpose feature does not allow for the exposure of child methods or properties

I have a main component and subcomponent set up as shown below: Main Component : <script setup> import SubComp from '@/components/SubComp.vue' import { ref, computed } from 'vue' const subComp = ref(null) const handleClick = () ...

MD-List Equilibrium Elevation

Seeking a solution for implementing a simple chat using the md-list template. The issue arises when new items are added to the md-list, causing it to expand. Desiring the list to behave similarly to other chat platforms, where the height remains constant ...

Transform an SVG string into an image source

Is there a way to convert an incoming string ' ' into an img src attribute and then pass it as a prop to a child component? I attempted the following method, but it hasn't been successful. `let blob = new Blob([data.payload], {type: &apos ...

Automatically compute and convert currency formats using JavaScript

May I ask again? Hopefully you understand. I am looking to automatically calculate with a money format. Here is a demo: https://jsfiddle.net/xp4ky2gg/ This is my code... HTML code <table style="width:100%"> ...

Unusual shadow effects with three.js

I'm still new to three.js and webgl, and I'm encountering some odd-looking shadows when using a directional light. Could somebody help me out? Below is the code I have for the renderer: this.renderer.shadowMapEnabled = true; this.renderer.shad ...

What is the best way to send a Rails AJAX form upon clicking?

I'm looking to implement AJAX form submission in Rails using a button. Here's my current code: Controller: def list @events = ExternalEvent.all if !params[:city_id].nil? @events = @events.where(city_id: params[:city_id]) end respond ...

What methods does JUMflot use to update points or select items? Interested in adding objects to an array and redrawing them without altering the original item

My goal is to use a button to push a line into an array and have JUMflot redraw those lines without affecting the original line being pushed in. Initially, I attempted this using the following code snippet (the generator ID represents the button and optio ...

javascript inquiry about if statements

function checkValidity() { startChecked = false; finishChecked = false; alert("startChecked: " + startChecked); alert("finishChecked: " + finishChecked); if (document.dd.start.checked.length == undefined || document.dd.finish.checked. ...

The Vuex mutation is not triggering the commit of payload information

I have developed a VueJS application that utilizes a Vuex store: const store = new Vuex.Store({ state: { organization: {} }, mutations: { loadOrganization (state, payload) { state.organization = payload.organization; ...

Displaying an HTML string on a webpage

I am developing a user dashboard using Django for a Python-based web application. This web application generates emails, and the HTML content of these emails is stored in a file (and potentially in a database table as well). As part of the dashboard's ...

The jQuery .next() function is applying a class to each element

I am struggling with adding a class to the <a> elements in my Bootstrap 4 Carousel when the slider changes. Currently, my code successfully adds the class .highlight to the next <a> elements, but it adds it to all subsequent elements. Addition ...

Changing an array in JavaScript within a function

When working with arrays in JavaScript, how can I mutate the value of an array inside a function? I'm aware that certain array methods can achieve this, but regular assignment doesn't seem to work. var arr = [4]; function changeArray(arr) { ...