DEV Community

Discussion on: React and components, axios

Collapse
 
tqbit profile image
tq-bit • Edited

Then try the following, given you have axios installed

  • Add a folder called 'mixins' to your project
  • Create a new file called myAxios.js inside of it
  • Add the following code to it:
import axios from 'axios';

// Replace the baseUrl with your backend root path
const myAxios = axios.create({
 baseUrl: 'http://localhost:3000/api',
 timeout: 1000,
 headers: {},
});

export default myAxios;
Enter fullscreen mode Exit fullscreen mode

Then, in the component in which you'd like to use the instance:

  • Import the 'myAxios' instance
  • Use the normal http methods to target your api's endpoints
  • If you need customized options, you can add them here as well, they'll be merged with the ones of the instance
// On top of your component
import appInstance from '@/mixins/myAxios.js';

// Inside your component's methods. Replace /endpoint with your path:
appInstance.get('/endpoint').then(response => console.log(response.data))
Enter fullscreen mode Exit fullscreen mode

I've only tried this in Vue and Vanilla, in React it cannot be too different though :)