Search code examples
javascriptvue.jsaxiosvuex

Vuex axios issue array updates


I'm currently having an issue with VueJS vuex and Axios :

I'm getting an array with axios -> looping on that array to populate its childs this way : "Rubriques" has a lot of self relations so one rubrique can have a multiple child rubrique

ACTIONS :

  actions: {
    get_main_rubriques: ({ commit }) => {
      axios.get('http://localhost:8180/unv-api/rubrique/search/rsql?query=niveau==1')
        .then(resp => {
          let results = resp.data._embedded.rubriques
          results.forEach(element => {
            axios.get('http://localhost:8180/unv-api/rubrique/search/rsql?query=idpere==' + element.id)
              .then((result) => {
                element.childs = result.data._embedded.rubriques
              })
              .catch((err) => {
                console.log(err)
              })
          })
          console.log(results)
          commit('MUTE_MAIN_RUBRIQUES', results)
        })
        .catch(err => {
          console.log(err)
        })
    }
  }

Mutations :

MUTE_MAIN_RUBRIQUES: (state, rubrique) => {
      state.rubriques = rubrique
    }

APP.VUE

computed: {
    ...mapState([
      'rubriques'
    ])
  },
  created: function () {
    this.$store.dispatch('get_main_rubriques')
  }

<b-dropdown  v-for="item in rubriques" :key="item.id"  v-bind:text="item.libelle" id="ddown1" class="m-md-1">
       <b-dropdown-item-button v-for="child in item.childs" :key="child.id"  v-bind:text="child.libelle">
         {{ child.id }} - {{ child.libelle }}
       </b-dropdown-item-button>
</b-dropdown>

Issue is : the parent dropdown are displaying without any problem but childs are not, they are not present in the state either BUT they are present in the console.log(results) before the commit in my action.

Am I doing something wrong ? Thanks.


Solution

  • move commit('MUTE_MAIN_RUBRIQUES', results) to sit inside the inner then block, to make sure it will get executed after you get back the response:

      actions: {
        get_main_rubriques: ({ commit }) => {
          axios.get('http://localhost:8180/unv-api/rubrique/search/rsql?query=niveau==1')
            .then(resp => {
              let results = resp.data._embedded.rubriques
              results.forEach(element => {
                axios.get('http://localhost:8180/unv-api/rubrique/search/rsql?query=idpere==' + element.id)
                  .then((result) => {
                    element.childs = result.data._embedded.rubriques;
                    console.log(results);
                    commit('MUTE_MAIN_RUBRIQUES', results);
                  })
                  .catch((err) => {
                    console.log(err)
                  })
              })
            })
            .catch(err => {
              console.log(err)
            })
        }
      }
    

    to understand why its not working on your way, read more about promises and asynchronous operation.