Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vue-Select: How can I convert this fetch() code to use axios?

I am trying to use the vue-select package in my application. I have some code that I copied from the docs and it works fine. However, I would like to convert it to use axios instead of fetch() for readability and also so I can use my own axios configuration settings.

How can I convert the following code to use axios instead of fetch?

    search: debounce((loading, search, vm) => {
      fetch(
        `https://api.github.com/search/repositories?q=${escape(search)}`
      ).then((res) => {
        res.json().then((json) => (vm.options = json.items))
        loading(false)
      })
    }, 350)

I tried the below code but I got an error: Uncaught (in promise) TypeError: res is not a function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    search: debounce(async (loading, search, vm) => {
      await axios
        .get(`https://api.github.com/search/repositories?q=${escape(search)}`)
        .then((res) => {
          res((json) => (vm.options = json.items))
          loading(false)
        })
    }, 350)

>Solution :

You’re calling res() as a function when it’s an object. You likely meant res.json() coming from fetch. This shouldn’t be necessary with axios, you can access the json with res.data.

Also you’re mixing promise/async which suprisingly doesn’t throw an error (.then() shouldnt be defined after awaiting), but makes the code tough to read. Use one or the other.

Async

{
    search: debounce(async (loading, search, vm) => {
        let res = await axios.get(`https://api.github.com/search/repositories?q=${escape(search)}`)
        const items = res.data
        vm.options = items
        loading(false)
    }, 350)
}

Promise

{ 
    search: debounce((loading, search, vm) => {
        axios
            .get(`https://api.github.com/search/repositories?q=${escape(search)}`)
            .then((res) => {
                const items = res.data
                vm.options = items
                loading(false)
            })
    }, 350)
}

IMO I find fetch() easier to read, plus it has native support.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading