Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Last active April 26, 2016 07:08
Show Gist options
  • Save mgtitimoli/17a36ff97e3a0ed5eddceec9cfc1ef78 to your computer and use it in GitHub Desktop.
Save mgtitimoli/17a36ff97e3a0ed5eddceec9cfc1ef78 to your computer and use it in GitHub Desktop.
Temporary gist (I will publish a npm module soon) that contains all the necessary files to use in combination with redux-thunk to handle asynchronism in redux
import defineConstant from "./define-constant";
export default function createActionCreator(type) {
function create(payload, meta) {
const action = {
type,
payload
};
if (payload instanceof Error) {
action.error = true;
}
if (meta !== undefined) {
action.meta = meta;
}
return action;
}
defineConstant(create, "TYPE", type);
return create;
}
import defineConstant from "./define-constant";
import createActionCreator from "./create-action-creator";
export default function createAsyncActionCreator(TYPE, asyncTask) {
const TYPE_STARTED = TYPE + "_STARTED";
const TYPE_FAILED = TYPE + "_FAILED";
const TYPE_SUCCEED = TYPE + "_SUCCEED";
const actionCreators = {
[ TYPE_STARTED ]: createActionCreator(TYPE_STARTED),
[ TYPE_FAILED ]: createActionCreator(TYPE_FAILED),
[ TYPE_SUCCEED ]: createActionCreator(TYPE_SUCCEED)
};
function create(...args) {
return async (dispatch, getState) => {
const startedAt = new Date();
dispatch(actionCreators[TYPE_STARTED](null, {
startedAt
}));
try {
const result = await asyncTask(...args, getState, dispatch);
dispatch(actionCreators[TYPE_SUCCEED](result, {
startedAt,
endedAt: new Date()
}));
return result;
}
catch (error) {
dispatch(actionCreators[TYPE_FAILED](error, {
startedAt,
endedAt: new Date()
}));
throw error;
}
};
}
Object
.entries({
TYPE_STARTED,
TYPE_FAILED,
TYPE_SUCCEED
})
.forEach(entry => defineConstant(create, ...entry));
return create;
}
export default function defineConstant(destObj, name, value) {
return Object.defineProperty(destObj, name, {
value,
enumerable: false,
writable : false
});
}
import createAsyncActionCreator from "./create-async-action-creator";
export default createAsyncActionCreator("USER.FETCH", async id => {
const response = await fetch("/api/user/" + id);
const user = await response.json();
return user;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment