Taking data from Xios and vuejs

Asked

Viewed 625 times

3

I have a very strange problem, I have the following code inside a component of Vuejs.

I am developing a system where I choose the options through several checkboxes, and pass their id to that my component below.

And I use Axios to request the database and retrieve the data I need.

See below for the component.

<template>
    <div>
        <ul>
            {{ modulos_encontrados }}
        </ul>
    </div>
</template>

<script>

export default {
    props:['turmas_checked'],
    data () {
        return {
            modulos:[]
        }
    },
    computed:{
        modulos_encontrados(){
            if(this.turmas_checked.length > 0){     
                  axios.get(`/modulos/${this.turmas_checked}`)
                .then(response => {
                    this.modulos = response.data;
                });
            }
        }

    }
}
</script>

And if I call the this.modulos out of the then(), I have the result I want, but it stays in an infinite looping, making requests through the Xios, and I put myself inside the then of course will not return anything.

Does anyone know how I can retrieve what I want from the Axios result and list within that same component ??

  • Console.log(this.turmas_checked) returns what?

  • Returns the ids I need, the queries in the database I can do normally, the problem is to list these results in the template, and when I do a Return out of then() it is making infinite requests.

1 answer

3


You mustn’t use computed thus, the computed is ideal for synchronous logic and should be a pure function.

Uses the watch to follow changes in turmas_checked and with imediate: true to run the Watcher when the component mounts.

The code could go like this:

<template>
  <div>
    <ul>
      {{ modulos_encontrados }}
    </ul>
  </div>
</template>

<script>
export default {
  props: ['turmas_checked'],
  data() {
    return {
      modulos: [],
    };
  },
  computed: {
    modulos_encontrados() {
      const length = this.modulos.length;
      return `Encontrados ${length} modulo${length === 1 ? 's' : ''}.`;
    },
  },
  watch: {
    message: {
      immediate: true,
      handler() {
        if (this.turmas_checked.length > 0) {
          axios.get(`/modulos/${this.turmas_checked}`).then((response) => {
            this.modulos = response.data;
          });
        }
      },
    },
  },
};
</script>
  • Hello Sergio, I saw your solution, and at first it didn’t work, but I changed a few things and now it was, thank you, I should put the solution here for those who need it most ?

  • @Alexandrecardoso is great! If there was an error in my reply you can comment that I correct, but it is worth commenting on your adaptation in my reply if it is useful to others. If it’s just a little thing, it’s not worth creating another answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.