Home > Blockchain >  How to re-render inner component when data from parent changes in Vue.js
How to re-render inner component when data from parent changes in Vue.js

Time:10-08

I'm trying to fetch some data from an API when some value is updated in a parent component, then use it in a child component. I tried several things but none worked.

Here's a simplified version of my components:

Parent

<template lang="html">
<div id="wrapper">
    <h4>My Super Component</h4>
    <button v-on:click="setListID">Load another list</button>
    <ChildComponent :usernames="usernames"></ChildComponent>
</div>
</template>

<script>
import ChildComponent from "./ChildComponent.vue"

export default {
    components: {
        ChildComponent
    },
    data() {
        return {
            listID: 0,
            usernames: undefined,
        }
    },
    watch: {
        listID: function(newID) {
            this.usernames = getUsernames(newID)
        }
    },
    methods: {
        setListID() {
            let id =  prompt("Input the list ID");
            if (Number.isNaN(id)) {
                alert("Please input a valid number");
            } else {
                this.listID = id;
            }
        }
    },
    async mounted() {
        this.usernames = await getUsernames(this.listID)
    }
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// Simulating an API call
async function getUsernames(listID) {
    sleep(200).then(() => {
        switch (listID) {
            case 0:
                return ['Pierre', 'Paul', 'Jaques']
            case 1:
                return ['Riri', 'Fifi', 'Loulou']
            case 2:
                return ['Alex', 'Sam', 'Clover']
            default:
                return []
        }
    })
}
</script>

Child

<template lang="html">
    <p v-for="username in usernames">{{username}}</p>
</template>

<script>
export default {
    props: {
        usernames: Object
    },
}
</script>

The props I get in the child is a Promise, I tried to pass an Array but as the function that fetches the data is async, and I can't await from watch, I'm kinda stuck.

UPDATE:

I think the issue comes from this code:

// Simulating an API call
async function getUsernames(listID) {
    await sleep(200).then(() => {
        switch (listID) {
            case 0:
                return ['Pierre', 'Paul', 'Jaques']
            case 1:
                return ['Riri', 'Fifi', 'Loulou']
            case 2:
                return ['Alex', 'Sam', 'Clover']
            default:
                return []
        }
    })
    return 'returned too early'
}

The function always returns 'returned too early'. When I remove this default return, undefined is returned and my child component uses it as the array.

CodePudding user response:

Try like following snippet

Vue.component('Child', {
  template: `
    <div class="">
      <p v-for="username in usernames">{{username}}</p>
    </div>
  `,
  props: {
    usernames: Array
  },
})

new Vue({
  el: '#demo',
  data() {
    return {
      listID: 0,
      usernames: undefined,
    }
  },
  watch: {
    listID: async function(newID) {
      this.usernames = await this.getUsernames(newID)
    }
  },
  methods: {
    setListID() {
      let id =  prompt("Input the list ID");
      if (Number.isNaN(id)) {
        alert("Please input a valid number");
      } else {
        this.listID = Number(id);
      }
    },
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    getUsernames(listID) {
      return this.sleep(200).then(() => {
        switch (listID) {
            case 0:
                return ['Pierre', 'Paul', 'Jaques']
            case 1:
                return ['Riri', 'Fifi', 'Loulou']
            case 2:
                return ['Alex', 'Sam', 'Clover']
            default:
                return []
        }
      })
    }
  },
  async mounted() {
    this.usernames = await this.getUsernames(this.listID)
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div id="wrapper">
    <h4>My Super Component</h4>
    <button v-on:click="setListID">Load another list</button>
    <Child :usernames="usernames"></ChildComponent>
</div>
</div>

CodePudding user response:

Seems like an issue with props you sending array but in the child component you expecting object. try below code and see

<template lang="HTML">
  <p v-for="(username, index) in usernames" :key="index">{{username}}</p>

</template>

<script>
export default {
    props: {
        type: Object, // or Aarray
        default: () => {
          return {} // [] if the type is array
        }
    },
}
</script>
  • Related