Options
All
  • Public
  • Public/Protected
  • All
Menu

Module @interface-technologies/iti-react-core

Index

Type aliases

AsyncValidator

AsyncValidator<TValue>: (input: TValue) => CancellablePromise<ValidatorOutput>

Type parameters

  • TValue

Type declaration

    • The "contract" that all async validators must implement.

      Parameters

      • input: TValue

      Returns CancellablePromise<ValidatorOutput>

ITIDispatch

ITIDispatch: Dispatch<ITIAction>

UseSimpleAutoRefreshQueryProps

UseSimpleAutoRefreshQueryProps<TQueryParams, TResult>: Pick<UseSimpleQueryProps<TQueryParams, TResult>, "queryParams" | "query" | "shouldQueryImmediately" | "onResultReceived" | "onLoadingChange" | "debounceDelay"> & AutoRefreshOptions

Type parameters

  • TQueryParams

  • TResult

UseSimpleParameterlessAutoRefreshQueryProps

UseSimpleParameterlessAutoRefreshQueryProps<TResult>: Pick<UseSimpleQueryProps<undefined, TResult>, "query" | "onResultReceived" | "onLoadingChange"> & AutoRefreshOptions

Type parameters

  • TResult

UseSimpleParameterlessQueryProps

UseSimpleParameterlessQueryProps<TResult>: Pick<UseSimpleQueryProps<undefined, TResult>, "query" | "onResultReceived" | "onLoadingChange" | "onError">

Type parameters

  • TResult

Validator

Validator<TValue>: (value: TValue) => ValidatorOutput

Type parameters

  • TValue

Type declaration

ValidatorOutput

ValidatorOutput: string | undefined | null | React.ReactNode

If the value is valid, a validator should return something falsy (undefined, null, or ''). If the value is invalid, the validator should return validation feedback which will be displayed to the user. The validation feedback can be a string or a ReactNode (e.g. a JSX element).

There are two special values of ValidatorOutput:

  • ASYNC_VALIDATION_PENDING: The value should be considered invalid because async validation is in progress.
  • ASYNC_VALIDATION_DEBOUNCE_PENDING: The value should be considered invalid because async validation has not started yet.
  • INVALID_NO_FEEDBACK: The value is invalid but no feedback should be displayed because the reason why the input is invalid is being displayed somewhere else.

Variables

ASYNC_VALIDATION_DEBOUNCE_PENDING

ASYNC_VALIDATION_DEBOUNCE_PENDING: "ASYNC_VALIDATION_DEBOUNCE_PENDING" = 'ASYNC_VALIDATION_DEBOUNCE_PENDING'

ASYNC_VALIDATION_PENDING

ASYNC_VALIDATION_PENDING: "ASYNC_VALIDATION_PENDING" = 'ASYNC_VALIDATION_PENDING'

AdvancedPhoneNumberUtil

AdvancedPhoneNumberUtil: { formatter: (s: string) => { text: string }; lenWithCountryCode: number; template: string; visibleLen: number } = ...

Type declaration

  • formatter: (s: string) => { text: string }
      • (s: string): { text: string }
      • Parameters

        • s: string

        Returns { text: string }

        • text: string
  • lenWithCountryCode: number
  • template: string
  • visibleLen: number

INVALID_NO_FEEDBACK

INVALID_NO_FEEDBACK: "INVALID_NO_FEEDBACK" = 'INVALID_NO_FEEDBACK'

ItiReactCoreContext

ItiReactCoreContext: Context<ItiReactCoreContextData> = ...

A context that provides configuration values used by code within iti-react-core. You must wrap your application in with <ItiReactCoreContext.Provider>.

Validators

Validators: { email: () => Validator<string>; greaterThan: (x: number) => Validator<string>; greaterThanOrEqual: (x: number) => Validator<string>; integer: () => Validator<string>; lessThan: (x: number) => Validator<string>; lessThanOrEqual: (x: number) => Validator<string>; maxLength: (maxLength: number) => Validator<string>; minLength: (minLength: number) => Validator<string>; money: (options?: { allowNegative?: boolean }) => Validator<string>; number: () => Validator<string>; required: () => Validator<string> } = ...

Validators for string values. Each property on this object is a function that returns a Validator<string>.

const validators = [Validators.required(), Validators.integer(), Validators.greaterThan(0)]

Type declaration

defaultItiReactCoreContextData

defaultItiReactCoreContextData: DefaultItiReactCoreContextData = ...

Defaults for parts of ItiReactCoreContextData. Does not include defaults for properties where there is no reasonable default value.

Functions

combineValidatorOutput

formatAddressLine3

  • formatAddressLine3(partialAddress: { city: undefined | null | string; postalCode: undefined | null | string; state: undefined | null | string }): string
  • Formats the "city state zip" part of an address.

    Parameters

    • partialAddress: { city: undefined | null | string; postalCode: undefined | null | string; state: undefined | null | string }
      • city: undefined | null | string
      • postalCode: undefined | null | string
      • state: undefined | null | string

    Returns string

formatDateTimeConfigurable

  • formatDateTimeConfigurable(mo: Moment, options: { convertToLocal: boolean; dateTimeFormat: string; onlyShowDateIfNotToday: boolean; timeFormat: string }): string
  • A configurable function for formatting a moment.

    Parameters

    • mo: Moment

      any moment object

    • options: { convertToLocal: boolean; dateTimeFormat: string; onlyShowDateIfNotToday: boolean; timeFormat: string }
      • onlyShowDateIfNotToday: when true, does not display the day if mo is today
      • convertToLocal: if mo should be converted to local time
      • dateTimeFormat: format used if date & time are displayed
      • timeFormat: format used if only time is displayed
      • convertToLocal: boolean
      • dateTimeFormat: string
      • onlyShowDateIfNotToday: boolean
      • timeFormat: string

    Returns string

formatDollars

  • formatDollars(amount: undefined | null | number): string

formatPercent

  • formatPercent(amount: undefined | null | number, purpose: "display" | "userInput", precision?: number): string
  • Formats a number as a percent. An input value of 1 means 100%.

    Supports negative values.

    Parameters

    • amount: undefined | null | number
    • purpose: "display" | "userInput"

      'display' if this percentage will be displayed, 'userInput' if percent will be used as the default value for a text input.

    • precision: number = 2

    Returns string

formatPhoneNumber

  • formatPhoneNumber(phoneNumber: undefined | null | string): string

formatPostalCode

  • formatPostalCode(postalCode: undefined | null | string): string

getCombinedValidatorOutput

getGuid

  • getGuid(): string

getPage

  • getPage<T>(allItems: T[], page: number, pageSize: number): T[]

getSubmitEnabled

  • getSubmitEnabled(formIsValid: boolean, showValidation: boolean): boolean
  • Returns a boolean indicating if a form's submit button should be enabled.

    Returns true if formIsValid === true or showValidation === false.

    This has the effect of disabling the submit button while async validation is in progress if validation is being shown.

    Parameters

    • formIsValid: boolean
    • showValidation: boolean

    Returns boolean

getTotalPages

  • getTotalPages(itemCount: number, pageSize: number): number

hasIErrorProperties

  • hasIErrorProperties<TType>(obj: unknown): obj is IError<TType>

isCanadianPostalCode

  • isCanadianPostalCode(postalCode: undefined | null | string): boolean

isRunningAsJestTest

  • isRunningAsJestTest(): boolean

normalizePhoneNumber

  • normalizePhoneNumber(phoneNumber: string): string

normalizePostalCode

  • normalizePostalCode(postalCode: undefined | null | string): string

nullToUndefined

  • nullToUndefined<T>(x: undefined | null | T): T | undefined

preventNonExistentPage

  • preventNonExistentPage(options: { firstPage?: 0 | 1; page: number; pageHasItems: boolean; onPageChange: any }): void
  • Use this whenever doing server-side paging to account for items being deleted while the user has the list open. Without this function, the user could see an empty page because the number of items, and thus the total number of pages, has decreased.

    Part of usePaginationHelpers. Usually not used directly.

    Parameters

    • options: { firstPage?: 0 | 1; page: number; pageHasItems: boolean; onPageChange: any }

    Returns void

resetPageIfFiltersChanged

  • resetPageIfFiltersChanged<TQueryParams>(queryParams: TQueryParams, newQueryParams: TQueryParams, firstPage?: 0 | 1, selectFilters?: (queryParams: TQueryParams) => Partial<TQueryParams>): TQueryParams
  • Compares the filters between the current query params and the new query params and resets to the first page if any of the filters have changed.

    Part of usePaginationHelpers. Usually not used directly.

    Type parameters

    • TQueryParams: { page: number; pageSize?: number }

    Parameters

    • queryParams: TQueryParams
    • newQueryParams: TQueryParams
    • firstPage: 0 | 1 = 1
    • selectFilters: (queryParams: TQueryParams) => Partial<TQueryParams> = ...

      determines which properties of the query params object are considered filters. By default, everything other than page and pageSize is considered a filter.

        • (queryParams: TQueryParams): Partial<TQueryParams>
        • Parameters

          • queryParams: TQueryParams

          Returns Partial<TQueryParams>

    Returns TQueryParams

toDecimalHours

  • toDecimalHours(hours: number, minutes: number): number

toHoursAndMinutes

  • toHoursAndMinutes(decimalHours: number): { hours: number; minutes: number }

undefinedToNull

  • undefinedToNull<T>(x: undefined | null | T): T | null

useCancellablePromiseCleanup

  • useCancellablePromiseCleanup(): CaptureCancellablePromise
  • Returns a capture function which "captures" CancellablePromise's and cancels them when the component unmounts. This prevents "set state after unmount" warnings.

    const capture = useCancellablePromiseCleanup()

    // Later, in an async function:
    const result = await capture(api.get('xyz'))

    Returns CaptureCancellablePromise

useControlledValue

useFieldValidity

useFieldValidityCore

  • useFieldValidityCore(options: { defaultValue: undefined | FieldValidity; onValidChange: undefined | ((valid: boolean) => void); fieldValidityIsValid: any }): { allFieldsValid: boolean; fieldValidity: FieldValidity; onChildValidChange: any }

usePrevious

  • usePrevious<T>(value: T): T | undefined
  • Stores and returns the previous value of something. Useful in niche situations. Internally, it uses useRef.

    const previousLocation = usePrevious(location)
    

    Type parameters

    • T

    Parameters

    • value: T

    Returns T | undefined

useSimpleAutoRefreshQuery

  • deprecated

    Performs a query on mount and repeats the query according to refreshInterval.

    Example:

    const { doQuery, doQueryAsync } = useParameterlessAutoRefreshQuery<WorkDocId, WorkDocDto>({
    queryParams: workDocId,
    query: (id) => api.workDoc.get({ id }),
    shouldQueryImmediately: (prev, cur) => true,
    onResultReceived: (workDoc) => {
    setWorkDoc(workDoc)
    dispatch(setShowBackendUnreachableAlert(false))
    },
    refreshInterval: dayjs.duration(1, 'minute'),
    onConnectionError: () => dispatch(setShowBackendUnreachableAlert(true))
    })

    Type parameters

    • TQueryParams

      the parameters of the query

    • TResult

      the type returned by the query

    Parameters

    Returns UseSimpleQueryReturn

useSimpleParameterlessAutoRefreshQuery

  • deprecated

    Performs a query on mount and repeats the query according to refreshInterval. Use this when query doesn't depend on any outside variables, e.g. props.

    Example:

    const { doQuery, doQueryAsync } = useParameterlessAutoRefreshQuery<WorkDocDto>({
    query: api.workDoc.getcount,
    onResultReceived: (count) => {
    setCount(count)
    dispatch(setShowBackendUnreachableAlert(false))
    },
    refreshInterval: moment.duration(1, 'minute'),
    onConnectionError: () => dispatch(setShowBackendUnreachableAlert(true))
    })

    Type parameters

    • TResult

      the type returned by the query

    Parameters

    Returns UseSimpleQueryReturn

useSimpleParameterlessQuery

useSimpleQuery

  • deprecated

    Except for use by useAsyncValidator.

    Perform a query on mount and whenever queryParams change.

    • queryParams: must be referentially stable, otherwise there will be an infinite loop. useMemo is helpful here.
    • query: must be not depend on outside variables, e.g. props!!! Changing query does not cause the query to rerun.
    • shouldQueryImmediately: provide a function here that takes in the previous query params and the current query params and return false if you want debouncing to occur.
    • onError: only needs to be provided if this query has custom error-handling logic. If not provided, the onError from ItiReactCoreContext will be used.

    Example:

    const { doQuery, doQueryAsync } = useSimpleQuery<number, WorkDocDto>({
    queryParams: workDocId,
    query: (id) => api.workDoc.get({ id }),
    shouldQueryImmediately: (prev, cur) => true,
    onResultReceived: (workDoc) => {
    setWorkDoc(workDoc)
    }
    })

    Type parameters

    • TQueryParams

      the parameters of the query

    • TResult

      the type returned by the query

    Parameters

    Returns UseSimpleQueryReturn

    an object containing doQuery and doQueryAsync functions. doQueryAsync must be called within a try-catch.

useValidation

  • A hook that allows implementing validation in any input component.

    Internally, useValidation calls useMemo on validators and asyncValidator since those props won't have stable identities if defined during the render as is typical. If useValidation did not do this, every component that rendered a validated component would have to call useMemo on validators and asyncValidator (or move the definitions outside of the component) to prevent infinite useEffect loops.

    If and when your validators or asyncValidator do change, you must pass a different validationKey for useValidation to pick up the changes.

    Type parameters

    • TValue

      the type of the input's value

    Parameters

    Returns ValidatorOutput

waitForReactUpdatesFactory

  • waitForReactUpdatesFactory(act: (f: () => Promise<void>) => PromiseLike<void>): (options?: { ms?: number; updateCount?: number }) => Promise<void>
  • To be used with Jest fake timers. Lets timers and React component async updates run.

    import { act as reactAct } from '@testing-library/react'
    import { act as hooksAct } from '@testing-library/react-hooks'
    import { waitForReactUpdatesFactory } from '@interface-technologies/iti-react/src/TestHelpers'

    export const waitForReactUpdates = waitForReactUpdatesFactory(reactAct)
    export const waitForHookUpdates = waitForReactUpdatesFactory(hooksAct)

    Parameters

    • act: (f: () => Promise<void>) => PromiseLike<void>
        • (f: () => Promise<void>): PromiseLike<void>
        • Parameters

          • f: () => Promise<void>
              • (): Promise<void>
              • Returns Promise<void>

          Returns PromiseLike<void>

    Returns (options?: { ms?: number; updateCount?: number }) => Promise<void>

      • (options?: { ms?: number; updateCount?: number }): Promise<void>
      • Parameters

        • Optional options: { ms?: number; updateCount?: number }
          • Optional ms?: number
          • Optional updateCount?: number

        Returns Promise<void>

Generated using TypeDoc