Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

raidboss's avatar

Vuex watch module state when populated by API

Hi there, I have a store that has a state that gets populated by my API (state name "results"), and I want to do an action whenever that state changes. I have a similiar mechanism with another vuex store but it works because it is watching a state that changes due to user input and not an API call. So, how should I go about this?

//This is the module in question
const results_store = {
    namespaced : true,
    state: {
        results : []
    },
    actions: {
        async get_request({commit}, data){

            let formdata = new FormData();
          
            formdata.append("distritos", 2);



            const res = await axios.post('http://localhost:3500/api/search', formdata,
      {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Accept': 'application/json',
                },

            });


            this.state.results = res.data
            console.log(res.data)
        },
    },
}

Over in my component I have the following

mounted() {
        // Watch api
        this.$store.watch(()=> this.$store.state['results_store'].results,
            value => {
               console.log(value)
            },
            {
                deep : true
            })
    },

Again, I have the exact same code for another store where the state is controlled by a click of a button. Is this even possible? How can I call a method of a component in a vuex store, if this is not possible? Thank you in advance

0 likes
1 reply
raidboss's avatar
raidboss
OP
Best Answer
Level 1

I am replying to my own question. Apperantly, the state was only updating the store but if you acessed it from anywhere else it would return empty (default state). So what I did was, much like the other example, I needed to populate the variable using a mutation and not an action. Hope this enlightens someone reading this.

Please or to participate in this conversation.