0

I am sending the following data to my reducer:

const data = {
  value: { age, gender, ethnicity },
  field: 'accessCode',
  actionType: 'ADD_DETAILS',
};

this.props.dispatch(formHandler(data));

How can I check to see if the value prop is a single value, or an object with three values?

My action:

export function formHandler(data) {
    return function(dispatch) {
        // check data.value is an object with three value 
        if (..) {
            this.props.dispatch(
                showError({
                    type: 'SHOW_MODAL',
                    modalType: 'SHOW_ERROR',
                })
            );
        } else {
            dispatch({
                type: data.actionType,
                field: data.field,
                value: data.value,
            });
        }
    };
}

My reducer to update state:

switch (action.type) {
    case ADD_LANGUAGE:
    case ADD_ACCESSCODE:
    case ADD_ACCESSCODE:
    case ADD_DRINKS_CONCERN:
      return {
        ...state,
        [action.field]: action.value,
      };
    case ADD_DETAILS:
      return {
        ...state,
        ...action.value,
      };
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
Bomber
  • 10,195
  • 24
  • 90
  • 167
  • use typeof to check the type of the variable, if you want to check how many values object have then check the count of keys `Object.keys(obj).length` – Mayank Shukla Aug 09 '17 at 17:54

2 Answers2

2

Concerning the comment of how to check, this could be a start.

if (typeof(data.value) === 'object' && Object.keys(data.value).length === 3)

I'm not exactly sure how specific your needs are (does it need to be exactly 3 keys for example), but feel free to expand and I can chime in.

Christopher Messer
  • 2,040
  • 9
  • 13
0

If you are okay using the Object prototype, you can test using this:

    Object.getOwnPropertyNames(data).length

Object.getOwnPropertyNames returns an array with all property values with a length property of it's own included.

Teedub
  • 372
  • 1
  • 7