refun
Version:
A collection of React Hook-enabled functions that compose harmoniously with each other. Similar to `recompose`, but:
1 lines • 2.91 kB
Source Map (JSON)
{"version":3,"sources":["redux-state-factory.ts"],"names":["ReduxStateFactory","context","mapStateToProps","stateKeysToWatch","props","EMPTY_OBJECT","rerender","prevStateRef","prevStatePropsRef","store","onMountRef","NOOP","current","newState","getState","subscribe","EMPTY_ARRAY"],"mappings":";;;;;;;;;;;AAAA;;AAGA;;AAEA;;AAEO,IAAMA,iBAAiB,GAAG,SAApBA,iBAAoB,CAAIC,OAAJ;AAAA,SAAmC,UAA8BC,eAA9B,EAAiEC,gBAAjE;AAAA,WAClE,UAACC,KAAD,EAA8B;AAAA,sBACP,qBAASC,kBAAT,CADO;AAAA;AAAA,UACnBC,QADmB;;AAE5B,UAAMC,YAAY,GAAG,mBAAUF,kBAAV,CAArB;AACA,UAAMG,iBAAiB,GAAG,mBAAWH,kBAAX,CAA1B;AACA,UAAMI,KAAK,GAAG,uBAAWR,OAAX,CAAd;AACA,UAAMS,UAAU,GAAG,mBAAmBC,UAAnB,CAAnB;;AAEA,UAAIH,iBAAiB,CAACI,OAAlB,KAA8BP,kBAAlC,EAAgD;AAC9C,YAAMQ,QAAQ,GAAGJ,KAAK,CAACK,QAAN,EAAjB;AAEAP,QAAAA,YAAY,CAACK,OAAb,GAAuBC,QAAvB;AACAL,QAAAA,iBAAiB,CAACI,OAAlB,GAA4BV,eAAe,CAACW,QAAD,CAA3C;AACD;;AAED,UAAIH,UAAU,CAACE,OAAX,KAAuBD,UAA3B,EAAiC;AAC/BD,QAAAA,UAAU,CAACE,OAAX,GAAqB;AAAA,iBAAMH,KAAK,CAACM,SAAN,CAAgB,YAAM;AAC/C,gBAAMF,QAAQ,GAAGJ,KAAK,CAACK,QAAN,EAAjB;;AAEA,gBAAI,CAAC,+BAAmBP,YAAY,CAACK,OAAhC,EAAyCC,QAAzC,EAAmDV,gBAAnD,CAAL,EAA2E;AACzEK,cAAAA,iBAAiB,CAACI,OAAlB,GAA4BV,eAAe,CAACW,QAAD,CAA3C;AAEAP,cAAAA,QAAQ,CAAC,EAAD,CAAR;AACD;;AAEDC,YAAAA,YAAY,CAACK,OAAb,GAAuBC,QAAvB;AACD,WAV0B,CAAN;AAAA,SAArB;AAWD;;AAED,4BAAUH,UAAU,CAACE,OAArB,EAA8BI,iBAA9B;AAEA,wCACKZ,KADL,EAEKI,iBAAiB,CAACI,OAFvB;AAID,KAnCiE;AAAA,GAAnC;AAAA,CAA1B","sourcesContent":["import { useContext, useRef, useEffect, useState } from 'react'\nimport type { Context } from 'react'\nimport type { Store } from 'redux'\nimport { EMPTY_OBJECT, EMPTY_ARRAY, NOOP } from 'tsfn'\nimport type { TExtend } from 'tsfn'\nimport { shallowEqualByKeys } from './utils'\n\nexport const ReduxStateFactory = <S>(context: Context<Store<S>>) => <P extends {}, SP extends {}>(mapStateToProps: (state: S) => SP, stateKeysToWatch: (keyof S)[]) =>\n (props: P): TExtend<P, SP> => {\n const [, rerender] = useState(EMPTY_OBJECT)\n const prevStateRef = useRef<S>(EMPTY_OBJECT)\n const prevStatePropsRef = useRef<SP>(EMPTY_OBJECT)\n const store = useContext(context)\n const onMountRef = useRef<() => void>(NOOP)\n\n if (prevStatePropsRef.current === EMPTY_OBJECT) {\n const newState = store.getState()\n\n prevStateRef.current = newState\n prevStatePropsRef.current = mapStateToProps(newState)\n }\n\n if (onMountRef.current === NOOP) {\n onMountRef.current = () => store.subscribe(() => {\n const newState = store.getState()\n\n if (!shallowEqualByKeys(prevStateRef.current, newState, stateKeysToWatch)) {\n prevStatePropsRef.current = mapStateToProps(newState)\n\n rerender({})\n }\n\n prevStateRef.current = newState\n })\n }\n\n useEffect(onMountRef.current, EMPTY_ARRAY)\n\n return {\n ...props,\n ...prevStatePropsRef.current,\n }\n }\n"],"file":"redux-state-factory.js"}