Avoiding Full URLs

Learn how to avoid passing full URLs to prevent code bloat and make it easier to run in different environments.

Passing full URLs from each action creator might cause code bloat and make it harder to run in different environments. Action creators should only pass the relative path of the URL, and API middleware should combine it with a constant set at build time:

axios.get(process.env.BASE_URL + action.payload.url);

// Alternatively, create an axios client with a predefined base URL
// const client = axios.create({ baseURL: process.env.BASE_URL });

Therefore our code from the previous lesson becomes:

const fetchUser = id => ({
  type: API,
  payload: {
    url: `/user/${id}`,
    onSuccess: setUserData
  }
});

const fetchComments = id => ({
  type: API,
  payload: {
    url: `/user/${id}/comments`,
    onSuccess: setComments
  }
});

Note: In this chapter, we will be using just the url parameter, assuming that BASE_URL is already defined for us.

Get hands-on with 1200+ tech skills courses.