Skip to content
Advertisement

While using GET method, can I convert query string to Object and send to an endpoint?

I’m using Axios for HTTP request and using useState hook for query string value.

const url = `${BASE_URL}/courses?page=${currentPage}&count=${contentCount}&lastContentId=${lastContentId}&search=${searchVal}`

axios.get(url)
.then((res) => console.log(res))

For now, I send every query string inside url variable. However, what I’m trying to do is:

    const url = `${BASE_URL}/courses?`
    const queryObj: any = {
      page: currentPage,
      count: contentCount,
      lastContentId : lastContentId,
      search: searchVal,
    }
    axios
      .get(url, queryObj)
      .then((res) => console.log(res))

convert into this format. However, it is not working.

What I want to know is whether it is possible or not to convert query string to object and how it can be done.

Advertisement

Answer

Did you read the docs

Second argument of get is options which have multiple parameters params included

const queryObj: any = {
  page: currentPage,
  count: contentCount,
  lastContentId : lastContentId,
  search: searchVal,
}
axios
  .get(url, { params: queryObj })
  .then((res) => console.log(res))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement