Sometimes we write too much repetition in our action creators.
For example:
export const fetchProducts = () => ({
type: FETCH_PRODUCTS
})
export const fetchProductsSuccessful = payload => ({
type: FETCH_PRODUCTS_SUCCESSFUL,
payload
})
export const fetchProductsFailure = error => ({
type: FETCH_PRODUCTS_FAILURE,
payload: error
})
export const fetchUsers = () => ({
type: FETCH_USERS
})
export const fetchUsersSuccessful = payload => ({
type: FETCH_USERS_SUCCESSFUL,
payload
})
export const fetchUsersFailure = error => ({
type: FETCH_USERS_FAILURE,
payload: error
})
You can see that we are repeating the same patterns in all our actions!
This library tries to remove this repetition encapsulating common actions in an action generator, like so:
import reshort from "reshort";
const productsActions = reshort("Products");
const usersActions = reshort("Users");
Install using your package manager:
npm install --save reshort
Then you can create your action creators in one line and use them after!
import reshort from "reshort";
const productsActions = reshort("Products");
productsActions("request")
// {
// type: "GET_PRODUCTS"
// }
productsActions("success", {test: 123})
// {
// type: "GET_PRODUCTS_SUCCESSFUL",
// payload: { test: 123 }
// }
productsActions("fail", {test: "error"})
// {
// type: "GET_PRODUCTS_FAILURE",
// payload: { test: "error" }
// }
Add the defined prefix to the constants of the three actions.
const productsActions = reshort("Products", {
prefix: "FETCH"
});
productsActions("request")
// {
// type: "FETCH_PRODUCTS"
// }
productsActions("success", {test: 123})
// {
// type: "FETCH_PRODUCTS_SUCCESSFUL",
// payload: { test: 123 }
// }
productsActions("fail", {test: "error"})
// {
// type: "FETCH_PRODUCTS_FAILURE",
// payload: { test: "error" }
// }
Add the defined suffix to the constant of the "success" action.
const productsActions = reshort("Products", {
successSuffix: "WITH_SUCCESS"
});
productsActions("success", {test: 123})
// {
// type: "FETCH_PRODUCTS_WITH_SUCCESS",
// payload: { test: 123 }
// }
Add the defined suffix to the constant of the "error" action.
const productsActions = reshort("Products", {
failSuffix: "REJECTED"
});
productsActions("fail", {test: "error"})
// {
// type: "FETCH_PRODUCTS_REJECTED",
// payload: { test: "error" }
// }
MIT © Robson Porto