DEV Community

Bret
Bret

Posted on

React and components, axios

With react, and a reusable, or reactive component..... is there a default Axios layout? That you just add the desired code you want? Or is it suppose to be different?

I have a snippet for a component, useComponent type of setup, but.... is a basic template ideal? Or should it be different?

Top comments (3)

Collapse
 
tqbit profile image
tq-bit • Edited

I'm not sure if I got your question right. Axios is an http client, which represents the business logic of sending requests to - and receiving responses from your backend. You might add it as part of a component. I don't think it makes sense to use it as such standalone.

Perhaps you're striding to create an axios instance, which you can then require as a mixin for one or more components. Or add it directly to it as a method.

Collapse
 
yobretyo profile image
Bret

I mean that as in to use it, like a JS file of Info.js and SetInfo.js

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 :)