react-nativeapibase-url

React native a common Base URL


How to maintain a BASE URL common and access anywhere within the project in react native. Now currently i call api individual & need to simplify code structure.


Solution

  • You can create an instance of API

    const instance = axios.create({
      baseURL: 'https://some-domain.com/api/',
      timeout: 1000,
      headers: {'X-Custom-Header': 'foobar'}
    });
    

    Now call the API's like

    axios.get(url[, config])
    axios.post(url[, data[, config]])
    

    This will help in creating a common base URL with common headers and you can import the API anywhere to invoke.

    Edit
    There does exist any method to create an instance of axios API. But you can do this to maintain a global base URL

    export const BASE_URL = "https://myurl.com"
    axios.get(BASE_URL + "/path")