Skip to content

Instantly share code, notes, and snippets.

@Andaeiii
Last active August 15, 2022 08:34
Show Gist options
  • Save Andaeiii/7a67d39d138d1f1f626cb3bda4bf7fab to your computer and use it in GitHub Desktop.
Save Andaeiii/7a67d39d138d1f1f626cb3bda4bf7fab to your computer and use it in GitHub Desktop.
lets say you want to intercept your axios request and also trigger redux-reducers in the process, this is the way to go about it...
import axios from "axios";
import * as config from './Settings'; //get app settings..
import { store } from '../index';
//initialize headers...
const headers = { 'Content-type': 'application/json; charset=UTF-8' };
//use interceptors to catch all axios events.. loading events...
// Add a request interceptor
axios.interceptors.request.use(function (config) { // Do something before request is sent
store.dispatch({ type: 'AJAX_PROGRESS' }); //dispatch events to the redux-store
return config;
}, function (error) {
//store.dispatch({ type: 'AJAX_COMPLETE' });
return Promise.reject(error); // Do something with request error
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
store.dispatch({ type: 'AJAX_COMPLETE' });
return response; // Do something with response data
}, function (error) {
//store.dispatch({ type: 'AJAX_COMPLETE' });
return Promise.reject(error); // Do something with response error
});
//implement public apis...
export const allPosts = () => axios.get(`${config.root_url}/posts`, headers);
export const createPost = (post) => axios.post(`${config.root_url}/posts`, post);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment