1

Where would I store the API URI centrally in a ReactJS Application? The URI only changes between environments and should be easily configurable (i.e. through environment variables).

I have looked into this package and into the new Context API, but am unsure it's the best way to achieve this. I have also looked into dotenv, but I don't like that I would have to use process.env.REACT_APP_SERVICE_URI in every component that wants to access the API. What is the usual approach?

I am not using Redux.

El Mac
  • 3,256
  • 7
  • 38
  • 58
  • There is no need to store the API URI in redux store and if I understand the question you don't need to pass the URI to all components. when you use redux actually you need to send your request from your "actions". – Sepehr Apr 16 '18 at 07:01
  • 1
    I wrote I am not using Redux and I am not planning to use it. – El Mac Apr 16 '18 at 07:22
  • 1
    You can use the config to store the baseURL for the changing it dynamically and then you can use a common function which will use fetch which can be called whenever you want to call an api. – Yash Thakur Apr 16 '18 at 07:34
  • How did you solve it? :) – klimat Apr 24 '18 at 06:58
  • @mklimek Right now I just read from env variables in each container I need to access the API. That won't stay like that for too long, though. I will have to think about something new. – El Mac Apr 24 '18 at 12:28

1 Answers1

4

I don't think you need an external dependency to do that.

I usually create simple module called api-client.js, which is responsible for calls to external API and defining endpoints.

In your case you might have:

import axios from 'axios' // some http client lib

const endpoint = process.env.REACT_APP_SERVICE_URI? process.env.REACT_APP_SERVICE_URI : 'https://foo.api.net/'

export default {
  getAllProducts () {
      return axios.get(endpoint + 'products').then(response => {
        log.debug(`api client fetched ${response.data.length} items`)
        return response.data
      }).catch(err => {
        log.error(err.message)
        throw err
      })
    } 
  },
  getProductById (id) {
    ...
  },
}

You read process.env.REACT_APP_SERVICE_URI only once.

I like to put this module inside api directory (and any other API related stuff).

klimat
  • 24,711
  • 7
  • 63
  • 70
  • 1
    Good approach. I was first going to do a "services" approach like this, but I understand you [try to keep the functionality with the components in React](https://stackoverflow.com/questions/35855781/having-services-in-react-application/35858927#35858927). The `dotenv` dependency is already included in `create-react-app` (I forgot to add that I am using that). Maybe I will change to a service-based approach in the future. – El Mac Apr 16 '18 at 10:25
  • Keep it simple until you *really* need something more. – klimat Apr 16 '18 at 10:36