l14045
l14045

Reputation: 63

Vue router with fetch data

How would I go on to fetch the id as parameter, when using params (not query) on router.push?

I assume my example is not optimal. How would I do it in a better way?

const Cities = Vue.component('city', {
    template: '<h1>{{  }}</h1>',
    created() {
      fetch('')
      .then((response) => response.json())
      .then((result) => {
  
        this.$router.push({ path: "/:id", params: {  } });
        this.cities = result
        console.log(this.cities)
      });

    },
    data() {
      return {
        cities: { 
          name: "",
          id: ""
        }
      }
    }
});

const router = new VueRouter({
  routes: [
    {
      component: Cities,
      path: '/:id'
    }
  ]
});



new Vue({
  el: '#app'
router

Upvotes: 1

Views: 936

Answers (1)

turbopasi
turbopasi

Reputation: 3605

Convert Array into Object by id

I am just focusing on displaying the city name here. So you get your result back from the request, I assume the reponse looks like this :

[
  {
    id : "9123102873",
    name : "Alpha"
  },
  {
    id : "1928307239",
    name : "Delta"
  }
]

One option would be to create a map out of the array, like


fetch(' ')
.then((response) => response.json())
.then((result) => {
       
  const cityMap = {};
  result.map((city) => {
    cityMap[city.id] = city;
  });
  this.cities = cityMap;

});

so it looks like

{
  "9123102873" : {
    id : "9123102873",
    name : "Alpha"
  },
  "9123102873" : {
    id : "1928307239",
    name : "Delta"
  }
}

Now you can render a city by id like

<h1> {{ cities[$route.params.id].name }} </h1>

Careful

🚧 But this will probably raise an error since the moment you are entering this component, cities[whatever].name will still be undefined until the request is done.

🚧 It's also not a good practice to fetch all cities everytime you visit this route, just too filter out one specific city afterwards. Maybe the API supports fetching one city directly ? Or you can take a look at VUEX

Upvotes: 1

Related Questions