Just about every vue demo that I have done on this blog has involved Axios. I am not sure that it is necessarily needed all the time, though. I wanted to take this blog post as an opportunity to see if it can be replaced with fetch.
Let’s start with last week’s mapping demo.
If you look on line 50 of the javascript side, you will see:
axios.get("https://api.wisparks.jws.app/v1/wisconsinParks.json").then(response=> (this.parks = response.data));
This is a pretty standard get request to our JSON API. When the response comes back, the value is placed within this.parks
. So, now, let’s refactor it to replace that with fetch.
As you can see above, the only real difference is that the same line of javascript now looks like:
fetch('https://api.wisparks.jws.app/v1/wisconsinParks.json', {method: 'get'}).then(response => response.json()).then(data => this.parks = data);
There isn’t a great difference in how readable it is and the project now has one fewer dependency. So, how compatible is fetch with modern browsers?
As long as you don’t care about Internet Explorer, it is pretty compatible. Since Internet Explorer is going out of support on June 15, 2022, that might not be a huge deal but it’s more of a personal choice than anything.
Have any questions, comment, etc? Feel free to drop a comment, below.
Top comments (1)
I like Axios specifically because it's better TypeScript support (e.g. axios.get<SomeResult>() is awesome.