TKoL
TKoL

Reputation: 13912

Axios - get url with parameters without actually making request

I have a bit of code in my React project that looks like this:

        const url = '/create-label-shipments.json';
        const filters = Object.assign({}, this.state.filters);
        filters.page = this.state.page;
        const response = await axios.get(url, {params: filters});

Now I know that axios takes that params object and creates a new url with query parameters, like '/create-label-shipments.json?page=1&date=2020-03-20&etc...'

What I am hoping I can do is call some axios function in a different part of my code that does exactly like above, but instead of making the request and giving me the response, it just gives me the URL.

        const url = '/create-label-shipments.csv';
        const filters = Object.assign({}, this.state.filters);
        const url = await axios.getUrl(url, {params: filters});
        // at this point, no request was made, and url === '/create-label-shipments.csv?page=1&date=2020-03-20&etc...'

Upvotes: 8

Views: 8089

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50874

Perhaps you're after axios#getUri(), which you could use by adding the params property and the url property to the config object passed to the method:

const params = {
  page: 1,
  date: '2020-03-20'
}

const url = '/create-label-shipments.csv';
const res = axios.getUri({url, params});

console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js" integrity="sha256-T/f7Sju1ZfNNfBh7skWn0idlCBcI3RwdLSS4/I7NQKQ=" crossorigin="anonymous"></script>

Upvotes: 15

Related Questions