DEV Community

Discussion on: Who's looking for open source contributors? (October 22nd edition)

Collapse
 
robbporto profile image
Robson Porto • Edited

Reshort - write less in your action creators!

Intro

Hi, everyone! I developed this simple little lib (my first lib!) to help me reduce some repetition in my action creators. If you have any constructive critiques I would be very pleased to hear it. If you have some interest in the project and can help, it would be awesome!

The problem:

Let's say that I want to fetch a list of books. Using redux, I have to create three actions creators:

  1. the first one is the "REQUEST";
  2. the second one is the "SUCCESS";
  3. the third one is the "FAIL".

Like so:

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!

Now let's say that I want to fetch a list of authors. Or a list of books. Or a list of bookmarks... This pattern of REQUEST-SUCCESS-FAIL can become very repetitive and verbose.

The solution

Using reshort you can create one "complete action creator" using one line, instead of three. Like so:

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" }
// }