Reputation: 455
I am developing react app and for api call i am using axios library. For all api calls i have app.js file, and then when some component needs to make api call just call function from that file. In short that would be little structre for now. In app.js file i have multiple api calls in which i am also seanding header config cause of token authorization. So i want to have a separate config file which will have default api header and all urls i am using for api call. I am looking for a best way to structure code.
Upvotes: 1
Views: 3855
Reputation: 2860
You can use a Component, which hold's your baseURL ( API base location )
Base URL Component:
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://react-test-b1ae5.firebaseio.com/'
});
export default instance;
Another file to hold you API calls part: You can give this component a desired name (Ex: axiousURL)
export const ADD_URL = 'AddArticle';
export const DELETE_URL = 'DeleteArticle';
export const UPDATE_URL = 'UpdateArticle';
Consuming:
import axios from '../../axios-orders';
import * as axiosURLS from '../../axiosURL';
axios.get( axios.baseURL+axiosURLS.DELETE_URL )
.then( response => {
// Some code//
} )
.catch( error => {
// handle error
} );
Upvotes: 2
Reputation: 2272
If you are using redux, I would take a look in this lib redux-api-middleware.
I like to use it because it makes the code clear. Instead of use axios
, it uses fetch
to manage the requests.
Upvotes: 0