Skip to content

Instantly share code, notes, and snippets.

@webmasterdevlin
Last active March 14, 2019 02:55
Show Gist options
  • Save webmasterdevlin/a64ed6bf242f2f31024ca770bf39271b to your computer and use it in GitHub Desktop.
Save webmasterdevlin/a64ed6bf242f2f31024ca770bf39271b to your computer and use it in GitHub Desktop.
Redux Reducer : src/store/hero/hero-reducer.js
import * as types from "./hero-actions";
/*
initalize your state with default values
*/
let initialState = {
heroes: [],
fetching: false,
error: ""
};
/*
switch-cases of your Reducer
*/
export const heroReducer = (state = initialState, action) => {
switch (action.type) {
case types.LOAD_HEROES_REQUEST:
return { ...state, fetching: true };
case types.LOAD_HEROES_SUCCESS:
return { ...state, fetching: false, heroes: action.payload };
case types.LOAD_HEROES_FAIL:
return { ...state, fetching: false, error: action.payload };
case types.CREATE_HERO_REQUEST:
return { ...state, fetching: true };
case types.CREATE_HERO_SUCCESS:
return {
...state,
heroes: [...state.heroes, action.payload]
};
case types.CREATE_HERO_FAIL:
return { ...state, fetching: false, error: action.payload };
case types.UPDATE_HERO_REQUEST:
return { ...state, fetching: true };
case types.UPDATE_HERO_SUCCESS:
return {
...state,
fetching: false,
heroes: state.heroes.map(hero =>
hero.id === action.payload.id ? action.payload : hero
)
};
case types.UPDATE_HERO_FAIL:
return { ...state, fetching: false, error: action.payload };
case types.DELETE_HERO_REQUEST:
return { ...state, fetching: true };
case types.DELETE_HERO_SUCCESS:
return {
...state,
heroes: state.heroes.filter(hero => hero.id !== action.payload),
fetching: false
};
case types.DELETE_HERO_FAIL:
return { ...state, fetching: false, error: action.payload };
default:
return state;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment