1

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

7
  • When you use params in $router.push you can then later access those params inside the component with this.$route.params.id for example. I am not sure if you mean that, so just commenting for now. Commented Jan 18, 2021 at 19:23
  • thanks for commenting. I am about to fetch and from each object, i'll use the "id" as the parameter, and "name" to render on the page Commented Jan 18, 2021 at 19:25
  • 1
    Well, you cannot rely on cities[1], because cities won't be loaded until your fetch resolves. Vue will complain about undefined property errors. First you should check if cities is set and then iterate each city: <div v-if="cities"><div v-for="city in cities">{{city.name}}</div></div>, also, what you define in the data function is a mismatch, it should be an empty array of cities instead of 1 object with id and name. Commented Jan 18, 2021 at 19:39
  • You not want to iterate over all cities in the template right ? You just want to display one specific city ? Commented Jan 18, 2021 at 19:57
  • yes so I want to display the {{name}} of the city that matches the id of the parameter. they should come from the same object. so the id and city name will match Commented Jan 18, 2021 at 20:03

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.