Sawtaytoes
10/8/2018 - 6:28 AM

Redux-like `FormValidationState` Component

A Redux-like API for creating stateful container components without the need to spin up or manage a store, subscriptions, or anything else.

import createRenderProps from './utils/createRenderProps'
import createReducer from './utils/createReducer'
import createStateSubscriber from './utils/createStateSubscriber'

export const VALIDATE_FIELDS = 'VALIDATE_FIELDS'

export const actions = {
  validateFields: ({
    fieldNames,
    formElement,
  }) => ({
    type: VALIDATE_FIELDS,
    fieldNames,
    formElement,
  }),
}

export const initialState = false

export const reducerActions = {
  [VALIDATE_FIELDS]: (
    prevState,
    {
      fieldNames,
      formElement,
    },
  ) => (
    fieldNames
    .map(fieldName => (
      formElement[fieldName]
      .value
    ))
    .every(Boolean)
  ),
}

export const isValidReducer = (
  createReducer(
    reducerActions,
    initialState,
  )
)

const namespacedReducers = {
  isValid: isValidReducer,
}

const FormValidationState = (
  createStateSubscriber(
    createRenderProps({
      actions,
      namespacedReducers,
    })
  )
)

export default FormValidationState