Skip to content

Instantly share code, notes, and snippets.

@VanTanev
Created June 14, 2019 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VanTanev/e2d7e933d5c22f2999053b02fc875aed to your computer and use it in GitHub Desktop.
Save VanTanev/e2d7e933d5c22f2999053b02fc875aed to your computer and use it in GitHub Desktop.
import fromPairs from 'lodash/fromPairs'
export type SafeForFormik<T extends { [key in string]: any }> = {
safe: { [keyWithoutDots in string]: T['key in string'] }
originalToSafeKeyDict: { [key in string]: string }
safeToOriginalKeyDict: { [keyWithoutDots in string]: string }
getBySafeKey: (data: T, keyWithoutDots: string) => T['key in string']
}
/**
* Because Formik tries to be smart about dots in Field names and
* treats them as lodash-like dot paths, we need to replace them.
* This is a utility function that given a `data` object like:
* {
* "http://example.com": "value"
* }
* returns:
* {
* safe: {
* "http://example-com": "value"
* },
* originalToSafeKeyDict: {
* "http://example.com": "http://example-com"
* },
* safeToOriginalKeyDict: {
* "http://example-com": "http://example.com"
* },
* getBySafeKey(data, safeKey) => data[originalKey]
* }
*/
export function safeFormikData<T extends { [K in string]: any }>(
data: T,
): SafeForFormik<T> {
const originalToSafeKeyDict = fromPairs(
Object.keys(data).map(key => [key, safeFormikName(key)]),
)
const safeToOriginalKeyDict = fromPairs(
Object.keys(data).map(key => [safeFormikName(key), key]),
)
const safe = fromPairs(
Object.keys(data).map(key => [originalToSafeKeyDict[key], data[key]]),
)
return {
safe,
originalToSafeKeyDict,
safeToOriginalKeyDict,
getBySafeKey: (data: T, keyWithoutDots: string) => {
const originalKey = safeToOriginalKeyDict[keyWithoutDots]
return originalKey && data[originalKey]
},
}
}
/**
* Convert a potentially unsafe attribute name with dots into one without dots.
* To be used with data generated by `safeFormikData()`
*/
export const safeFormikName = (string: string, replacement = '-'): string => {
return String(string).replace(/\./g, replacement)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment