How to dispatch action from .then() function in component method?


#1

Hello again.
When i async call provider.search (from leaflet-geosearch leaflet plugin) it needs to save result in vuex store.

addMarker(e) {
     const provider = new OpenStreetMapProvider()
     provider.search({query:[e.latlng.lat,e.latlng.lng]}).then(function(result){
      var OrderRoute = {frompoint: [e.latlng.lat,e.latlng.lng],fromlabel: result[0].label};
      console.log(OrderRoute)
      this.$store.dispatch("SET_ORDER_ROUTE",OrderRoute)
      }).catch(error => {
        console.log(error);
     }) 
    },

This code returns error
TypeError: “this is undefined” addMarker webpack-internal:///20:99:11

Action SET_ORDER_ROUTE works good out of ‘providers.search()’ block. Even console.log(OrderRoute) shows truly result of geosearching request.
How can i dispatch action with result of async call?


#2

Uwe an arrow function instead of a normal one for the callback in then()


#3

Thanks again, all works!