Skip to content

Instantly share code, notes, and snippets.

@webmasterdevlin
Last active March 14, 2019 00:58
Show Gist options
  • Save webmasterdevlin/337a9a52ac281befaafeb466c0c73861 to your computer and use it in GitHub Desktop.
Save webmasterdevlin/337a9a52ac281befaafeb466c0c73861 to your computer and use it in GitHub Desktop.
Redux Actions : src/store/hero/hero-actions.js
import { addHero, getHeroes, removeHero, updateHero } from "./hero-service"; // services of hero module
/*
* action types
*/
export const LOAD_HEROES_REQUEST = "LOAD_HEROES_REQUEST";
export const LOAD_HEROES_SUCCESS = "LOAD_HEROES_SUCCESS";
export const LOAD_HEROES_FAIL = "LOAD_HEROES_FAIL";
export const CREATE_HERO_REQUEST = "CREATE_HERO_REQUEST";
export const CREATE_HERO_SUCCESS = "CREATE_HERO_SUCCESS";
export const CREATE_HERO_FAIL = "CREATE_HERO_FAIL";
export const UPDATE_HERO_REQUEST = "UPDATE_HERO_REQUEST";
export const UPDATE_HERO_SUCCESS = "UPDATE_HERO_SUCCESS";
export const UPDATE_HERO_FAIL = "UPDATE_HERO_FAIL";
export const DELETE_HERO_REQUEST = "DELETE_HERO_REQUEST";
export const DELETE_HERO_SUCCESS = "DELETE_HERO_SUCCESS";
export const DELETE_HERO_FAIL = "DELETE_HERO_FAIL";
/*
* action creators
*/
export const loadHeroes = () => {
return async dispatch => {
dispatch({
type: LOAD_HEROES_REQUEST
});
try {
const { data, status } = await getHeroes(); // sends get request to backend service for retrieval of all heroes
dispatch({ type: LOAD_HEROES_SUCCESS, status, payload: data }); // sends the successful type of action to the reducer
} catch (error) {
dispatch({
type: LOAD_HEROES_FAIL,
payload: error.toString()
}); // sends the failure type of action to the reducer
}
};
};
export const postHero = hero => {
return async dispatch => {
dispatch({
type: CREATE_HERO_REQUEST
});
try {
await addHero(hero); // sends post request to the backend service to save a new hero
dispatch({ type: CREATE_HERO_SUCCESS, payload: hero }); // sends the successful type of action to the reducer
} catch (error) {
dispatch({
type: CREATE_HERO_FAIL,
payload: error.toString()
}); // sends the failure type of action to the reducer
}
};
};
export const putHero = hero => {
return async dispatch => {
dispatch({
type: UPDATE_HERO_REQUEST
});
try {
await updateHero(hero);
dispatch({ type: UPDATE_HERO_SUCCESS, payload: hero });
} catch (error) {
dispatch({
type: UPDATE_HERO_FAIL,
payload: error.toString()
});
}
};
};
export const deleteHero = id => {
return async dispatch => {
dispatch({
type: DELETE_HERO_REQUEST
});
try {
await removeHero(id);
dispatch({ type: DELETE_HERO_SUCCESS, payload: id });
} catch (error) {
dispatch({
type: DELETE_HERO_FAIL,
payload: error.toString()
});
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment