Kamor04
Kamor04

Reputation: 307

Axios get with params

I am trying to implement getting data from API with params. I got two functions for that and I can't see the error. Any ideas?

getFilteredProducts() {
    return apiClient.get('/product/', {
      params: {
        search: String(name)
      }
    })
  }
async fetchFilteredProducts({ commit }, name) {
      await productService.getFilteredProducts({name})
      .then(response => {
        commit('SET_FILTERED_PRODUCTS', response.data.items)
      })
      .catch(error => {
        console.log('Error has occured' + error)
      })
    }

I received working solutions with the code below, so the problem probably with the second parameter.

async fetchFilteredProducts({ commit }, name) {
      await axios.get("MY_API_URL/product/", {
        params: {
          search: String(name)
        }
      })
      .then(response => {
        commit('SET_FILTERED_PRODUCTS', response.data.items)
      })

Upvotes: 6

Views: 18825

Answers (1)

Ajay Gupta
Ajay Gupta

Reputation: 2033

It's not clear about what you are trying to accomplish but I think your functions should be like this:

Using Async/Await:

// Your Service
async getFilteredProducts(name) {
  return await apiClient.get('/product/', {
    params: {
      search: String(name)
    }
  })
}

// Using Your Service
async someParentFunction() {
    const response = await getFilteredProducts("John")
    console.log(response.data);
}

Using Promises:

// Your Service
getFilteredProducts(name) {
  return apiClient.get('/product/', {
    params: {
      search: String(name)
    }
  })
}

// Using Your Service
getFilteredProducts("John").then((response) => {
    console.log(response.data);
})

Do note the name parameter which I am passing to getFilteredProducts method. Previously this wasn't there so String(name) would result in an empty string "".

Upvotes: 9

Related Questions