Use AXIOS in an approval and production environment at the same time 🎯

Reading: 4 minutes.

Who said developing can’t be fun? If you’ve ever been torn between approval and production environments, with different URLs for your AXIOS requests, this blog post is for you! Let’s explore how to create a smart configuration file for AXIOS that automatically adapts to the environment in which you are working. Get ready for a more efficient and, of course, fun development journey!

Advantages of creating a file
for AXIOS configuration:

Setting up AXIOS can be like preparing a cake recipe: a little complicated, but with a delicious result. Imagine having a single file that handles all the peculiarities of the environment, adapting as necessary. The advantages are many:

Ease of Maintenance: With a dedicated configuration file, any necessary changes can be made centrally. No more searching for URLs lost in the code!

Flexibility of Environments: Switching between approval and production has never been easier. Your code will understand where it is and act accordingly.

Improved Readability: Your code is clearer and more concise when AXIOS settings are separated into their own file. Say goodbye to the tangle of configuration codes!

Let’s create our own magic file called api.js. See how it can be structured: 

// api.js
import axios from ‘axios’;

 

const baseURL = process.env.NODE_ENV === ‘production’
  ? ‘https://your-api-prod.com’
  : ‘http://localhost:8000’;

 

const axiosInstance = axios.create({
  baseURL: baseURL,
  headers: {
    ‘Content-Type’: ‘application/json’,

 

  },
});

 

export default axiosInstance;
 
Example for import the archive api.js in your VueX:
 
import api from ‘api.js’
export default {
    namespaced: true,
    state: {
        clients: null
    },
 
    getters: {
        getAllClients: (state) => state.clients
    },
    actions: {
        async getClients({ commit }) {
            try {
                const response = api.get(`getClients`)
                commit(‘setClients’, response)
                return response
            } catch (error) {
                throw new Error(error)
            }
        },
    },
    mutations: {
        setClients(state, clients) {
            state.clients = clients
        }
    }
}

Dynamics for Environments:

Sweet as a cupcake, this file automatically adjusts to its surroundings. If it’s in production, it goes to the correct URL; if it is being approved, it hits the target without wasting time.

Utilizar o AXIOS nunca foi tão divertido! Com um arquivo dedicado para a configuração, você ganha em clareza, eficiência e agilidade. Dê um passo à frente na organização do seu código e aproveite a tranquilidade de saber que seu ambiente está sendo tratado com a seriedade que merece, com uma pitada de humor no processo. Happy coding! 😄🚀

Leave A Comment