Bruno Quaresma
Bruno Quaresma

Reputation: 10707

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?

Upvotes: 0

Views: 125

Answers (1)

Dayvson Lima
Dayvson Lima

Reputation: 101

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 }}
  })
}

Upvotes: 1

Related Questions