You can create a separate service for fetch in your code and use it as a independent providers
Here is the httpRequest.js which you can use default fetch api:
import axios from 'axios';
class HttpRequest {
constructor(baseURL) {
this.axios = axios.create({
baseURL,
});
}
reponseInterceptor() {
// Add a response interceptor
this.axios.interceptors.response.use(
response => (
// Do something with response data
response
),
error => (
// Do something with response error
Promise.reject(error)
),
);
}
requsetInterceptor() {
this.axios.interceptors.request.use(
config => (
// Do something before request is sent
config),
error => (
// Do something with request error
Promise.reject(error)
),
);
}
fetch(url, params, config = {}) {
return this.axios.get(url, {
params,
...config,
});
}
create(url, data, config = {}) {
return this.axios.post(url, data, {
...config,
});
}
update(url, data, config = {}) {
return this.axios.put(url, data, {
...config,
});
}
patch(url, data, config = {}) {
return this.axios.patch(url, data, {
...config,
});
}
remove(url, params, config = {}) {
return this.axios.delete(url, {
params,
...config,
});
}
}
export default HttpRequest;
Here is how you can create your words.js services:
import config from 'config';
import HttpRequest from './httpRequest';
export default class WordService extends HttpRequest {
constructor(servicePath) {
super(config.markMeHost);
this.path = `${config.markMeHost}/${servicePath}`;
}
listWords() {
return this.fetch(this.path, {});
}
createWords(data) {
return this.create(this.path, data);
}
updateWords(data, id) {
return this.update(`${this.path}/${id}`, data);
}
deleteWords(id) {
return this.remove(`${this.path}/${id}`);
}
}
Your api service index.js:
import WordService from './words';
// Give arg to provider to start endpoint with specific path for example = abc.com/api/words
export default new WordService('words');
For further details you can check my github account for axios service https://github.com/m-nathani/markme/tree/master/frontend/src/service/api