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

Time:08-17

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:

<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?

CodePudding user response:

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

  }
}
  • Related