Search code examples
javascriptvue.jsvuexfetch-api

Why the fetching data Get request isn't returning several parameters, instead it returns a single one Vuex?


I'm expecting to get data and visualize a list with a fetch GET request, by passing two parameters. So I'm getting an error 400 when I pass two parameters, and I'm getting data ok when I'm passing a single one.

https://stackblitz.com/edit/vue-hrqfyc?file=src%2Fstore%2Findex.js,src%2FApp.vue,src%2Fcomponents%2FArrivalDate.vue,src%2Fcomponents%2FArrivalPoint.vue,src%2Fcomponents%2FDepartureDate.vue,src%2Fcomponents%2FDeparturePoint.vue,src%2Fcomponents%2FFlight.vue,src%2Fcomponents%2FFlightList.vue,src%2Fmain.js

This doesn't work

async getFlights(context, { selectedPoint, departurePoint }) {
    
  const res = await fetch(
    `http://api.travelpayouts.com/v2/prices/month-matrix?currency=rub&origin=${selectedPoint}&destination=${departurePoint}&show_to_affiliates&token=${context.state.token}`,
  );
  if (res.ok) {
    let result = await res.json();
    context.commit('setFlights', result.data);
  }
  return res.ok;
},

This works

async getFlights(context, selectedPoint }) {
    
  const res = await fetch(
    `http://api.travelpayouts.com/v2/prices/month-matrix?currency=rub&origin=${selectedPoint}&destination=LED&show_to_affiliates&token=${context.state.token}`,
  );
  if (res.ok) {
    let result = await res.json();
    context.commit('setFlights', result.data);
  }
  return res.ok;
},

This works

async getFlights(context, departurePoint }) {
    
  const res = await fetch(
    `http://api.travelpayouts.com/v2/prices/month-matrix?currency=rub&origin=LED&destination=${departurePoint}&show_to_affiliates&token=${context.state.token}`,
  );
  if (res.ok) {
    let result = await res.json();
    context.commit('setFlights', result.data);
  }
  return res.ok;
},

Solution

  • You can use vuex and create additional states for selected stuff, for example:

    state: {
      selectedArival: null,
      selectedDeparture: null,
      ...
    },
    

    then mutations for them:

    setSelectedArival(state, data) {
      state.selectedArival = data;
    },
    setSelectedDeparture(state, data) {
      state.selectedDeparture = data;
    },
    

    commit them on selection:

    choosePoint(point) {
      ...
      this.$store.commit('setSelectedDeparture', this.selectedPoint);
      // this.$store.commit('setSelectedArival', this.selectedPoint); from other component
      ...
      // before dispatching getFlights
    }
     
    

    and change action to:

    async getFlights(context) {
      const res = await fetch(
        `https://api.travelpayouts.com/v2/prices/month-matrix?currency=rub&origin=${context.state.selectedDeparture}&destination=${context.state.selectedArival}&show_to_affiliates=true&token=${context.state.token}`
      );
      ...
    }