Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run a function within a vue3 component when state within a Pinia store changes

I am trying to learn Vue3 + Pinia, and I have a Pinia store with an async action that fetches JSON data and saves it to state. In my Vue3 template, when that state changes (when we’ve retrieved the JSON data) I want to run some other function. How do I do this?

This is my store:

import { defineStore } from "pinia";

export const useMap = defineStore("map-store", {
  state: () => {
    return {
      locations: [],
      fetching: false,
    };
  },

  getters: {
    results(state) {
      return state.locations;
    },

    isFetching(state) {
      return state.fetching;
    },
  },

  actions: {
    async fetchLocations() {
      console.log("fetching locations");
      this.fetching = true;
      const response = await fetch("/data/locations.json");
      try {
        const result = await response.json();
        this.locations = result.locations;
        console.log(result.locations);
      } catch (err) {
        this.locations = [];
        console.error("Error loading new locations:", err);
        return err;
      }

      this.fetching = false;
    },
  },
});

This is my Vue3 template that uses that store:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script setup>
import { useMap } from "../store/map.js";
</script>

<script>
import { mapState, mapActions } from "pinia";

export default {
  computed: {
    ...mapState(useMap, { locations: "results" }),
  },

  methods: {
    ...mapActions(useMap, ["fetchLocations"]),
  },

  created() {
    this.fetchLocations();
  },

};
</script>

So what I want to do is, after this.fetchLocations retrieves the locations and saves them to state as this.locations, I want to run a method like addMarkers(){ //add markers to a map based on location data }.

How do I do this?

>Solution :

You can use the watch option to observe the state changes and run your method inside its handler :

watch:{
  locations:{
    handler(newVal,oldVal){
       this.addMarkers();
    },
    deep:true

  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading