aSmater.Me
aSmater.Me

Reputation: 1014

Redux-auto: action chaining vs index reducer

Can anyone tell me what the difference between using chain on a reducer function and doing work in the main index reducer function in redux-auto

I want to save an error,

A) store/chat/send.js

import actions from 'redux-auto'

//...

 function rejected(chat, payload, error){
  return chat;
} onError.chain = (c, p, error) => actions.logger.save(error)

//...

or

B) store/logger/index.js

import actions from 'redux-auto'
import save from './save'

export default function (errorsLog = [], action)
{
   if(action.type == actions.chat.send.rejected){
      return save(errorsLog,action.payload)
   }
   return errorsLog
}

They both work

My questions:

  1. I don't know what would be better. What is the difference?

  2. Why would I use one over the other?

  3. Also, can't I just call the action logger.save(...) inside the rejected. Why does this chain feature exist?

Thanks for any help :)

Upvotes: 0

Views: 145

Answers (2)

Brian
Brian

Reputation: 1036

A) Using the chain(OnError) will fire the action AFTER the source(rejected) reducer has completed. creating a new call across you store.

B) You are changing the state in the source reducer call

Your qustions:

1,2) Using chaining will make you code more readable as the next function is collocated with the source reducer, but but having it in the index group all action that will happen to that part of the store.

3) Calling an action function directly within a reducer function. Is an anti-pattern. This is dispatching an action in the middle of a dispatched action. The reducer will be operating on inconsistent data.

Upvotes: 0

Ivan Burnaev
Ivan Burnaev

Reputation: 2730

One of the main Redux point is predictability. We should use as more pure functions as possible. The reducer must not have any side-effects at all.

Recently I've worked on the same feature - error (user action, etc) logging. I think all of this actions are side-effects. They have no profit for user and can't be a part of main business logic.

That's why I use custom middleware to capture all actions I need to log. The action which I need to log I've marked with some meta-prop (ex. {log: 'errorLog'}) and in the middleware I checked every action. If it has a log prop then I make some logger magic.

Finally I've got clearly understandable code where all of logging side-effects incapsulated in middleware.

Upvotes: 0

Related Questions