Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

109
Visualizações
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:

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

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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

  }
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda