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

Time:07-31

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.

CodePudding user response:

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))

CodePudding user response:

The way you pass query parameters seems wrong according to this tutorial. Also, if you haven't taken a look at the axios api in npm, I highly recommend that.

  • Related