heppi75
heppi75

Reputation: 141

Vue component check if a vuex store state property is already filled with data

here is my setup. The state "categories" in the state is fetched async from a json endpoint.

In the component I want to work with this data, but if I reload the page the categories are always empty.

methods: {
        onSubmit() {
            console.log(this.filter);
        },
        formCats(items) {
            console.log(items);
            // const arr = flatten(data);
            // console.log(arr);
        }
    },
    created() {
        const data = this.categories;

        this.formCats(data);
    },
    computed: {
        ...mapState(['categories'])
    }

I also tried async created() with await this.categories. Also not working as expected! Would be great if someone could help me with this. Thanks!

Upvotes: 3

Views: 1737

Answers (1)

Dan
Dan

Reputation: 63059

This is happening because the async fetch doesn't finish until after the component is already loaded. There are multiple ways to handle this, here's one. Remove created and turn formCats method into a computed.

computed: {
  ...mapState(['categories']),
  formCats() {
    let formCats = [];
    if (this.categories && this.categories.length) {
      formCats = flatten(this.categories);
    }
    return formCats;
  }
}

formCats will be an empty array at first, and then it will immediately become your formatted categories when this.categories is finished fetching.

Upvotes: 1

Related Questions