Skip to content
Advertisement

URLSearchParams with axios instance in react-native

I was attempting to send payload, and URLSearchParams through an API URL from my react-native application. I initialized an axios instance as,

import { BASE_URL } from '../../utils/constants';
const axios = require('axios');

const api = axios.create({
    baseURL: BASE_URL,
    timeout: REQUEST_TIMEOUT,
    headers: {
        'content-type': 'application/json',
    },
});

And from another component, I imported the axios instance, then,

 import api from "../../utils/api"
 import { API_URL } from '../../utils/constants';

 requestAPI(userId, sessionId){
    let data = { "userId": userId, "sessionId": sessionId };
    
    api
      .post(API_URL, data)
      .then(response => {
        // handle the response
        // do stuffs
   })
}

The payload contains the request body for the API. As stated in API docs, I have to send the filters through URLSearchParams, like,

 api
   .post(API_URL?status=success&type=out, data)
   .then(response => .... {
       //handle the response and stuffs
   });

Any suggestions on how to send the URLSearchParams without hardcoding or just appending search queries to the API_URL? TIA.

Advertisement

Answer

Use a new URL() and assign the URLSearchParams() to the search property of the URL object.

You can then pass that object directly to axios

const API_URL ='https://httpbin.org/get',
      REQ_URL = new URL(API_URL);
      
const data = Object.entries({'foo':'bar', age:23}),      
      params = new URLSearchParams(data);
      
// to manually add params      
params.append('username', 'foobar');      
      
REQ_URL.search = params;


// example passing url object to fetch()
(async ()=>{
   console.log('REQ_URL :', REQ_URL)
   const req= await fetch(REQ_URL);
   const {args, url} = await req.json();
   console.log('URL from response:',url)
   console.log(args)
})()
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement