简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM