It’s easy to DRY in Redux!

Vo Thanh Dat
Aug 31, 2018 · 2 min read
Dry using sunlight :))

Have you ever felt that you repeat too much when writing redux? Regularly, when we fetch an api, we have to manage the process with 5 actions:

start

This call the action for start fetching from api

succeed

If the request succeeded (no throw error), call this

fail

If the request failed (throw error or not satisfy), call this.

cancel

Somehow, the request is calling, but we don’t what to listen to the result (even success or failure), call this to remove listening

reset

After the request is done already, call this to reset the status from ‘success’ or ‘failure’ to ‘ready’ in order to reset state through the listener from Component (as we often listen to the props.status through componentWillReceiveProps or shouldComponentWillUpdate)

In Wakumo Viet Nam, we work with more than 100 saga to process API fetching and more in the future. Every time we want to request for something, we have to repeat these work:

We repeat to create nearly the same actionTypes for every requests: 'START_TO_FETCH_SOME_THING'
'SUCCEED_TO_SOME_THING'
'FAIL_TO_FETCH_SOME_THING'
'CLEAR_FETCHING_SOME_THING'
'RESET_FETCHING_SOME_THING'

We repeat to create nearly the same actionCreators for every requests:
const startToFetchSomeThing = createAction(START_TO_FETCH_SOME_THING); const succeedToFetchSomeThing =createAction(SUCCEED_TO_FETCH_SOME_THING);
const failToFetchSomeThing = createAction(FAIL_TO_FETCH_SOME_THING); const clearFetchingSomeThing = createAction(CLEAR_FETCHING_SOME_THING); const resetToFetchSomeThing = createAction(RESET_TO_FETCH_SOME_THING);

We repeat to create nearly the same reducer for every requests:

const reducer = handleActions({  START_TO_FETCH_SOME_THING: (state, action) => ({...}),​  SUCCEED_TO_FETCH_SOME_THING: (state, action) => ({...}),​  FAIL_TO_FETCH_SOME_THING: (state, action) => ({...}),​  CLEAR_TO_FETCH_SOME_THING: (state, action) => ({...}),​  RESET_TO_FETCH_SOME_THING: (state, action) => ({...}),​}, initialState);

Thinking about managing about 100 redux saga like this will surely drive you crazy.

Let’s improve this:

Firstly, let’s divide actions to groups to make it easy to manage, create groupActions.js

Then, let’s make actions from the structure above, we will use function create-action from library ‘redux-actions’:

Then, we make root-reducer:

Let’s call it in Container:

or call it in Saga:

That’s all the tricks. Hope you guys find it helpful!

Vo Thanh Dat

Written by

A Developer at Wakumo Viet Nam. Love running, coding and traveling.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade