Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- FETCH_REQUEST // API promise is pending
- FETCH_SUCCESS // API promise resolved
- FETCH_FAILURE // API promise rejected
- export const loadEntity = (
- entity,
- dataPromise,
- ) => {
- if (!dataPromise || !dataPromise.then)
- throw new Error('dataPromise must be a Promise, and cannot be null/undefined');
- return (dispatch) => {
- // Notify UI of fetch request
- dispatch(apiRequest(entity)());
- return dataPromise
- .then(data => {
- // Dispatch success to update model state
- dispatch(
- apiSuccess(entity)(data)
- )
- })
- .catch(error => {
- // Dispatch failure to notify UI
- dispatch(
- apiFailure(entity)(error)
- )
- })
- }
- };
- export const apiRequest = (entity) => {
- return makeEntityActionCreator(FETCH_REQUEST, entity);
- };
- export const apiSuccess = (entity) => {
- return makeEntityActionCreator(FETCH_SUCCESS, entity, 'data');
- };
- export const apiFailure = (entity) => {
- return makeEntityActionCreator(FETCH_FAILURE, entity, 'error');
- };
- export function makeEntityActionCreator(type, entity, ...keys) {
- if (!type) throw new Error('Type cannot be null/undefined');
- if (!entity) throw new Error('Entity cannot be null/undefined');
- return function(...args) {
- let action = { type, entity };
- keys.forEach((arg, index) => {
- action[keys[index]] = args[index]
- });
- return action;
- }
- }
- export default function model (state = {}, action) {
- switch (action.type) {
- case FETCH_SUCCESS: // fall through
- case FETCH_FAILURE: // fall through
- case FETCH_REQUEST: {
- return {
- ...state,
- [action.entity]: entity(
- state[action.entity],
- action
- )
- }
- }
- default: {
- return state;
- }
- }
- }
- const INITIAL_ENTITY_STATE = {
- isFetching: false,
- lastUpdated: undefined,
- data: {}
- };
- function entity (
- state = INITIAL_ENTITY_STATE,
- action
- ) {
- switch (action.type) {
- case FETCH_REQUEST: {
- return {
- ...state,
- isFetching: true
- }
- }
- case FETCH_SUCCESS: {
- return {
- ...state,
- isFetching: false,
- lastUpdated: Date.now(),
- data: action.data
- }
- }
- case FETCH_FAILURE: {
- return {
- ...state,
- isFetching: false,
- lastUpdated: Date.now(),
- error: action.error
- }
- }
- default: {
- return state;
- }
- }
- }
- "model": {
- "fooEntity": {
- "isFetching": false,
- "data": ['foo','bar','from','server'],
- "lastUpdated": 1467308062465
- },
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement