Search code examples
vuejs2axiosvue-select

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:

    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.