UNPKG

refun

Version:

A collection of React Hook-enabled functions that compose harmoniously with each other. Similar to `recompose`, but:

1 lines 2.89 kB
{"version":3,"sources":["map-state.ts"],"names":["useState","useRef","EMPTY_OBJECT","shallowEqualByKeys","mapState","stateName","stateSetterName","getValue","watchKeys","props","prevProps","current","state","setState","nextState"],"mappings":";;AAAA,SAASA,QAAT,EAAmBC,MAAnB,QAAiC,OAAjC;AACA,SAASC,YAAT,QAA6B,MAA7B;AAEA,SAASC,kBAAT,QAAmC,SAAnC;AAEA,OAAO,IAAMC,QAAQ,GAAG,SAAXA,QAAW,CAA0DC,SAA1D,EAAyEC,eAAzE,EAA+FC,QAA/F,EAA0HC,SAA1H;AAAA,SACtB,UAACC,KAAD,EAA+E;AAAA;;AAC7E,QAAMC,SAAS,GAAGT,MAAM,CAAIC,YAAJ,CAAxB;;AAD6E,oBAEnDF,QAAQ,CAAIU,SAAS,CAACC,OAAV,KAAsBT,YAAtB,GAAqCK,QAAQ,CAACE,KAAD,CAA7C,GAAuDP,YAA3D,CAF2C;AAAA;AAAA,QAEtEU,KAFsE;AAAA,QAE/DC,QAF+D;;AAI7E,QAAIC,SAAS,GAAGF,KAAhB;;AAEA,QAAIF,SAAS,CAACC,OAAV,KAAsBT,YAAtB,IAAsC,CAACC,kBAAkB,CAACO,SAAS,CAACC,OAAX,EAAoBF,KAApB,EAA2BD,SAA3B,CAA7D,EAAoG;AAClG;AACA;AACA;AACAM,MAAAA,SAAS,GAAGP,QAAQ,CAACE,KAAD,CAApB,CAJkG,CAMlG;AACA;AACA;AACA;AACA;;AACA,UAAIK,SAAS,KAAKF,KAAlB,EAAyB;AACvBC,QAAAA,QAAQ,CAACC,SAAD,CAAR;AACD;AACF;;AAEDJ,IAAAA,SAAS,CAACC,OAAV,GAAoBF,KAApB;AAEA,6BACKA,KADL,wDAEGJ,SAFH,EAEeS,SAFf,mCAGGR,eAHH,EAGqBO,QAHrB;AAMD,GA/BqB;AAAA,CAAjB","sourcesContent":["import { useState, useRef } from 'react'\nimport { EMPTY_OBJECT } from 'tsfn'\nimport type { TExtend3 } from 'tsfn'\nimport { shallowEqualByKeys } from './utils'\n\nexport const mapState = <SN extends string, SSN extends string, P extends {}, R> (stateName: SN, stateSetterName: SSN, getValue: (props: P) => R, watchKeys: (keyof P)[]) =>\n (props: P): TExtend3<P, { [K in SN]: R }, { [K in SSN]: (arg: R) => void }> => {\n const prevProps = useRef<P>(EMPTY_OBJECT)\n const [state, setState] = useState<R>(prevProps.current === EMPTY_OBJECT ? getValue(props) : EMPTY_OBJECT)\n\n let nextState = state\n\n if (prevProps.current !== EMPTY_OBJECT && !shallowEqualByKeys(prevProps.current, props, watchKeys)) {\n // React will continue current render, delivering 'state', which is already old state.\n // By assigning to 'nextState', we deliver fresh state during current render.\n // After that React will rerender due to actual 'setState', delivering same state value.\n nextState = getValue(props)\n\n // React prevents rerender by setState if next value is the same as current state.\n // But in this case, setState is triggered during the render phase.\n // React does not interrupt render, and lets the component to render till the end,\n // and after that initiates next render caused by this setState.\n // Manually checking for equality to prevent unnecessary rerender.\n if (nextState !== state) {\n setState(nextState)\n }\n }\n\n prevProps.current = props\n\n return {\n ...props,\n [stateName]: nextState,\n [stateSetterName]: setState,\n // FIXME: https://github.com/Microsoft/TypeScript/issues/13948\n } as any\n }\n"],"file":"map-state.js"}