Skip to content

Instantly share code, notes, and snippets.

@marcuscaum
Created October 17, 2016 11:29
Show Gist options
  • Save marcuscaum/fc33136db69cef9b21128e6d9b8f4e46 to your computer and use it in GitHub Desktop.
Save marcuscaum/fc33136db69cef9b21128e6d9b8f4e46 to your computer and use it in GitHub Desktop.
import axios from 'axios';
const ROOT_URL = 'XXX';
const API_KEY = 'XXX';
export const FETCH_POSTS = generateActions('FETCH_POSTS');
export const CREATE_POST = generateActions('CREATE_POST');
export const FETCH_POST = generateActions('FETCH_POST');
export const DELETE_POST = generateActions('DELETE_POST');
// Generate object containing all actions states consts
function generateActions(type) {
return {
[type + '_REQUEST']: type + '_REQUEST',
[type + '_SUCCESS']: type + '_SUCCESS',
[type + '_FAILURE']: type + '_FAILURE'
};
}
// action creator to fetch all posts
export const fetchPosts = generateActionCreator('get', FETCH_POSTS);
// action creator to create a new post
export const createPost = generateActionCreator('post', CREATE_POST);
// action creator to fetch a specific post
export const fetchPost = generateActionCreator('get', FETCH_POST);
// action creator to delete a specific post
export const deletePost = generateActionCreator('delete', DELETE_POST);
// Generate our actions creators
function generateActionCreator(requestType, actionType, id, onSuccess = () => {}) {
return function actionCreator(par, onSuccess) {
const url = `${ROOT_URL}/posts/${typeof par === 'string' ? par : ''}?key=${API_KEY}`;
const request = axios[requestType](url, par);
const action = Object.keys(actionType).map((k) => actionType[k]);
return dispatch => {
dispatch({type: action[0]});
request.then(response => {
dispatch({type: action[1], payload: response});
if(onSuccess && typeof onSuccess === "function") {
onSuccess();
}
}).catch(error => {
dispatch({type: action[2], error});
});
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment