Search code examples
javascriptreduxflux

How can i improve this redux action creator?


I have this action:

import uuid from 'uuid'
import { findPaymentCategoryByName } from './Categories/selectors'
import { addPaymentCategory } from './Categories/actions'

export const addPayment = payment => (dispatch, getState) => {
  const id = uuid.v1()
  const { paymentCategory, ...paymentValues } = payment
  let existentPaymentCategory = findPaymentCategoryByName(getState(), paymentCategory.name)

  if(!existentPaymentCategory) {
    existentPaymentCategory = dispatch(addPaymentCategory(paymentCategory)).payload
  }

  dispatch({
    type: 'ADD_PAYMENT',
    payload: { payment: { ...paymentValues, id, paymentCategoryId: existentPaymentCategory.id }}
  })
}

his action creates a payment. When the category does not exist, it is created.

But I read that it is not nice to change two stores in an action. So, anyone knows how can i improve this action?


Solution

  • You can follow the principle: "Tell-Don't-Ask" The method "findPaymentCategoryByName" can be called "paymentCategoryByName" and himself take charge of creating the category to if it does not exist.

    More details about TellDontAsk here: http://martinfowler.com/bliki/TellDontAsk.html

    export const addPayment = payment => (dispatch, getState) => {
      const id = uuid.v1()
      const { paymentCategory, ...paymentValues } = payment
      let existentPaymentCategory = PaymentCategoryByName(getState(), paymentCategory.name)
    
      dispatch({
        type: 'ADD_PAYMENT',
        payload: { payment: { ...paymentValues, id, paymentCategoryId: existentPaymentCategory.id }}
      })
    }