Luca Spezzano
Luca Spezzano

Reputation: 380

Returning a getters in a computed create a loop

I am calling inside the computed an action from the store to run it and after I am returning a getter, this will create a loop.

The HTML

{{loadedProjects}}

The computed

computed: {
    loadedProjects() {
      this.$store.dispatch("getProjects");
      return this.$store.getters.loadedProjects;
    }
  }

The store

import Vuex from "vuex";
import axios from "axios";

const createStore = () => {
    return new Vuex.Store({
        state: {

            loadedProjects: []
        },
        mutations: {
            setProjects(state, projects) {
                state.loadedProjects = projects
            }

        },
        actions: {
            getProjects(vuexContext) {
                console.log("hello1")
                return axios.get("THE API URL")
                    .then(res => {
                        console.log("hello2")
                        vuexContext.commit("setProjects", res.data);
                    })
                    .catch(e => console.log(e));
            }

        },
        getters: {
              loadedProjects(state) {
                return state.loadedProjects;
              }
        }
    });
};

export default createStore;

I expect to call my action to populate my state and after to return my state to render my data.

Upvotes: 2

Views: 1365

Answers (3)

TheAlexLichter
TheAlexLichter

Reputation: 7299

Computed properties should not have side effects (e.g. calling a store action, changing data, and so on). Otherwise it can happen that the triggered side effect could lead to a re-rendering of the component and possible re-fetching of the computed property. Thus, an infinite loop

Upvotes: 1

Abdelillah Aissani
Abdelillah Aissani

Reputation: 3108

What is the point of using the store action that makes an API call inside the computed property ... maybe you want to trigger loadedProjects change ? ....computed property is not asynchronous so either way the return line will be executed before the you get the response... you might try vue-async-computed plugin OR just use the call on the created hook like you have done which is the better way and you don't have to use a computed property you can just {{ $store.getters.loadedProjects }} on your template

Upvotes: 2

Luca Spezzano
Luca Spezzano

Reputation: 380

I changed the code like that:

created: function () {
  this.$store.dispatch("getProjects")
},
computed: {
  loadedProjects() {
    return this.$store.getters.loadedProjects
  }
}

It is working now but I would like to know but I have that problem working inside the computed and also I wonder if it's the best solution. Any help????

Upvotes: 0

Related Questions