All files / modules/10-common/components/FormikEffect FormikEffect.tsx

100% Statements 13/13
100% Branches 2/2
100% Functions 4/4
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62              10x                       348x     348x 177x       348x                                         10x 348x 348x   348x   348x 329x       348x    
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import { useEffect, useRef } from 'react'
import type { FormikContext } from 'formik'
 
//
// Global onChange utility for Formik
// @see https://github.com/formium/formik/issues/1633#issuecomment-520121543
//
 
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function usePrevious(value: any): any {
  // The ref object is a generic container whose current property is mutable ...
  // ... and can hold any value, similar to an instance property on a class
  const ref = useRef()
 
  // Store current value in ref
  useEffect(() => {
    ref.current = value
  }, [value]) // Only re-run if value changes
 
  // Return previous value (happens before update in useEffect above)
  return ref.current
}
 
export interface FormikEffectOnChangeParams {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  prevValues: Record<string, any>
 
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  nextValues: Record<string, any>
 
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  formik: FormikContext<any>
}
 
export interface FormikEffectProps {
  onChange: ({ prevValues: prevValue, nextValues: nextValue, formik }: FormikEffectOnChangeParams) => void
 
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  formik: FormikContext<any>
}
 
export const FormikEffect: React.FC<FormikEffectProps> = ({ onChange, formik }) => {
  const { values } = formik
  const prevValues = usePrevious(values)
 
  useEffect(() => {
    // Don't run effect on form init
    if (prevValues) {
      onChange({ prevValues, nextValues: values, formik })
    }
  }, [prevValues, values, formik, onChange])
 
  return null
}