gertqin / vuex-class-modules

Typescript class decorators for vuex modules
MIT License
194 stars 20 forks source link

How to passing multiple arguments to @action #73

Closed wdpoppe closed 2 years ago

wdpoppe commented 2 years ago

Hi,

I'm completely stuck on an issue I encounter with passing multiple arguments through an action. I've tried my best to find a solution but my vuex/decorators experience is limited. Help is appreciated.

===My .ts file belonging to the vue component === function receives a (dynamic)number when clicking in a table and recieves a (dynamic) year when clicking.

 @raceResultsModule.Action
  loadRaceResults!: (year: any, round: any) => void;
getResults(round: number) {
    this.loadRaceResults(this.year, round);
  }

===My module .ts file with the action/axios call receives the passed dynamic values year and round===

@Action
  async loadRaceResults(data: { year: number; round: number }) {
    await axios
      .get(`http://localhost:8000/api/f1/${year}/${round}/results.json`)
      .then((response) => {
        this.raceResults = response.data.MRData.RaceTable.Races;
      })
      .catch((error) => console.log(error));
  }

If I console.log data I receive only one value(year) instead of two dynamic values(year + round). How can I accomplish this properly?

bodograumann commented 2 years ago

You have defined the action correctly, by using options parameter style. Being only able to pass one parameter is a restriction of vuex, btw. Now you be constistent and also call the action just as you have defined it. E.g.:

getResults(round: number) {
    this.loadRaceResults({ year: this.year, round });
}
wdpoppe commented 2 years ago

Great! You've clarified so much with this comment. The fact that Vuex has a restriction on passing only one parameter is essential to understand when passing multiple values. Your approach allows you to pass basically one value as on object with multiple properties.

I had to refine my code a bit and know happy to move forward! Thank you for helping me out.

@raceResultsModule.Action
  loadRaceResults!: (year?: any, round?: any) => void;
getResults(round: number) {
    this.loadRaceResults({ year: this.year, round });
  }
 @Action
  async loadRaceResults(result: { year: number; round: number }) {
    await axios
      .get(
        `http://localhost:8000/api/f1/${result.year}/${result.round}/results.json`
      )
      .then((response) => {
        this.raceResults = response.data.MRData.RaceTable.Races;
      })
      .catch((error) => console.log(error));
  }
}