Nicolas Bocquet
Nicolas Bocquet

Reputation: 25

Duplicate items in list after an API update

I'm learning vuejs and I'm doing a weather app, the goal is to rank cities with an index (humidex). I fetch weather information by API (axios) in order to collect data from several cities. I want to auto update data every x minutes, problem : some of my results are duplicated (the new data don't replace the old one).

I tried to set an unique key (based on latitude and longitude) for each item, it works for several results but not for all.

  data () {
    return {
      items:[],
      show: false,
      cities: cities,
      newCity:''
    } 
  },
  components: {
    Item
  },
  computed: {
    sortHumidex() {
      return this.items.slice().sort((a,b) => {
        return this.getHumidex(b) - this.getHumidex(a) || b.current.temp_c - a.current.temp_c
      })
    }
  },
  methods: {
    addCity() {
      if (this.newCity.trim().length == 0) {
        return
      }
      this.cities.push(this.newCity)
      this.newCity = ''
    },
    getHumidex: (el) => {
      const e = 6.112 * Math.pow(10,(7.5*el.current.temp_c/(237.7+el.current.temp_c)))
      *(el.current.humidity/100)
      return Math.round(el.current.temp_c + 5/9 * (e-10))
    },
    indexGeo: (e) => {
      const lat = Math.round(Math.abs(e.location.lat))
      const lon = Math.round(Math.abs(e.location.lon))
      return lat.toString() + lon.toString()
    },

    getApi: function () {
      const promises = [];

      this.cities.forEach(function(element){
        const myUrl = apiUrl+element;
        promises.push(axios.get(myUrl))
      });
      let self = this;

      axios
        .all(promises)
        .then(axios.spread((...responses) => {
          responses.forEach(res => self.items.push(res.data))
      }))
        .catch(error => console.log(error));
    }
  },
  created() {
    this.getApi()
    this.show = true
  }
}

The render when I update API :

screenshot

Upvotes: 1

Views: 405

Answers (1)

David Weldon
David Weldon

Reputation: 64332

By pushing to the existing array of items, you have to deal with the possibility of duplicates. This can be eliminated simply by replacing items every time the API call is made.

Replace:

responses.forEach(res => self.items.push(res.data))

with:

self.items = responses.map(res => res.data)

Upvotes: 1

Related Questions