Home > Software engineering >  Differences between data in vue
Differences between data in vue

Time:10-26

I have tried to figure out why this happens but I have no idea why. I am going to post the code and then explain what happens. The issue is I do not know WHY this happens and it's annoying me like crazy!

Button:

<a
  href="#"
  v-for="(userStories, userStoriesIndex) in storiesData"
  :key="userStoriesIndex"
  @click="openUserStories(userStoriesIndex)"
>

Which loads:

<Stories v-for="(userStories, userStoriesIndex) in storiesData" 
  :key="userStoriesIndex"
>
  <Story v-for="(story, storyIndex) in userStories.stories" 
    :key="storyIndex"
    user-link="#"
    :name="userStories.model.name"
    :date="story.created_at"
    close-button
    @closeButtonClick="onCloseButtonClick"
  >
    <template #avatar>
       <img :src="userStories.model.profile_photo_path" />
    </template>
    <img :src="story.media.preview_url" />
  </Story>
</Stories>

And storiesData is loaded from this method:

getStories() {
  axios
    .get("/stories")
    .then((response) => (this.storiesData = response.data));
}

which is loaded during mounted()

its loaded into:

data() {
        return {
            storiesData: [],

Now, when I click the button, the model loads incomplete, it is not loading the data... but... and this is where I lose it...

If I take the data from the Axios request, convert it to a JS object, and add it to the Vue file, everything works as intended.

I am not sure what's going on. I am completely at a loss why local would work and Axios would not. The data is IDENTICAL including but not limited to looking at Vue DevTools.

CodePudding user response:

This sound to me like a bad async handling, Axios (and any other AJAX library), send the request asynchronously. It look like you thought that the rendering would wait for the ajax request to finish, but it is not. Try convert the axios call into Async/Await:

async function getStories() {
  const data = await axios.get("/stories");

  return data;
}

or for short:

async function getStories() {
  return await axios.get("/stories");
}

then in your hydration function:

this.storiesData = await getStories();
  • Related