Singh
Singh

Reputation: 207

How to pass a query param in post call in Reactjs

I am new to reactjs.I am doing a post call but not sure, how to pass a boolean value in url as a query param in reactjs. For eg: http://www.abx.com?example=true. How do I pass this example in post api call. Endpoint: API_SAMPLE: "/sample",

post call:

postCall() {
    const config = {
      headers: {
        accept: "application/json",
        "Content-Type": "application/json",
      },
    };
    const data = {
      product: {
        body
      },

    };
    return http
      .post(this.API.API_SAMPLE, data, config)
      .then((response) => {
        return response.data;
      })
      .catch((error) => {
        throw error;
      });
  }

i want to add a boolean value in my query param, how will i do that

Upvotes: 0

Views: 1136

Answers (2)

Bassem
Bassem

Reputation: 4050

You can use template literals to pass the variable to your URL.

const example = true;
const url = `http://abx.com/sample?example=${example}`

or use it this way:

return http.post(`${this.API.API_SAMPLE}?example=${example}`, data, config) {...}

Upvotes: 2

Salmin Skenderovic
Salmin Skenderovic

Reputation: 1720

wether you are using POST or GET you will have to modify the URL. You can do this "dynamically" or you can use something like URLSearchParams: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

var URL = "http://example.com/search";
var searchParams = new URLSearchParams(URL);

searchParams.append("example", "true");

searchParams.toString() // "http://example.com/search?example=true";

Just make sure you support the correct browsers: https://caniuse.com/#search=urlsearchparams

Upvotes: 1

Related Questions