3

I am parsing a JSON data using axios to consume APIs with Vue.js. There is a field value 10, after 20 mins it can be updated to become 11.

I am following this code example: https://jsfiddle.net/jonataswalker/416oz6ga/

getFollowers() {
      return new Promise((resolve, reject) => {
        axios.get('https://api.github.com/users/octocat')
          .then(response => resolve(response))
          .catch(err => reject(error))
      });
 }

Similar to the followers in the above example I want my value to change automatically in my front-end.

How can I update this value in the front-end? Any suggestions?

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
Parkar
  • 2,800
  • 3
  • 15
  • 24
  • 3
    You'd probably have to use sockets to push those changes to the front-end. But explaining how to do that would be too broad for Q/A format. – Nisarg Shah Oct 31 '17 at 13:08
  • Okay, If I send request to api link after few mins interval, that will be a good approach ? – Parkar Oct 31 '17 at 13:17
  • Long polling is okay sometimes, but be careful with the interval you set. If the interval is too small, your server performance will suffer due to the number of requests coming from multiple users. – Nisarg Shah Oct 31 '17 at 13:27

2 Answers2

8

So, you have two ways you can do this.

One is to use websockets, which is a bidirectional connection from the client to your server. This requires specific configuration on your server, and you'd have to update your client code to handle the data push. A recent Medium post might be a good way for you to get started.

The other method is to use polling on the client. Use a timer such that for every N seconds, it makes a request to the API and updates with the response.

A good breakdown has already been written about the pros and cons of either.

Jason
  • 11,263
  • 21
  • 87
  • 181
  • Thanks , I am thinking about the Second option. Will that be a good approach ? – Parkar Oct 31 '17 at 13:21
  • it really depends on what the interval you set for, as was mentioned in the original question comments. You might find that lots of solutions are really dependent on outside factors, in which `it depends` is the only real answer – Jason Oct 31 '17 at 13:33
-1

you have no need to return a new promise because if this is in "methods", I'm not sure how you would treat this promise, but axios itself already returns a promise in your query, what you need to do is:

getFollowers() {
  axios.get('https://api.github.com/users/octocat')
  .then(response => this.$set(this, 'data', response.data))
  .catch(err => (throw error))
 }
isrmic
  • 1