URLSearchParams with axios in react-native

Tags: , ,



I was trying to request both request-body data, and URLSearchParams to my API in my react-native application. I initialized an axios instance as,

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

And from another screen, I imported the instance to invoke the requestAPI method as my needs,

 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 data contains request data for my API. I used separate view(s) & dropdown(s) for filtering the response data, and as of my API structure, I need to send the filter params as URLSearchParams, like,

 api
   .post(API_URL?status=success&type=out, data)
   .then(response => .... //handle the rest

From the dropdown components, I can set the filters to the current state. Any idea how to send the URLSearchParams to my axios instance without hardcoding the API_URL? Any suggestions would be appreciated

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


Source: stackoverflow