useLegacyStore.tsx 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import {useEffect, useState} from 'react';
  2. import Reflux from 'reflux';
  3. import {CommonStoreInterface} from './types';
  4. type LegacyStoreShape = Reflux.Store & CommonStoreInterface<any>;
  5. /**
  6. * This wrapper exists because we have many old-style enzyme tests that trigger
  7. * updates to stores without being wrapped in act.
  8. *
  9. * Wrting tests with React Testing Library typically circumvents the need for
  10. * this. See [0].
  11. *
  12. * [0]: https://javascript.plainenglish.io/you-probably-dont-need-act-in-your-react-tests-2a0bcd2ad65c
  13. */
  14. window._legacyStoreHookUpdate = update => update();
  15. /**
  16. * Returns the state of a reflux store. Automatically unsubscribes when destroyed
  17. *
  18. * ```
  19. * const teams = useLegacyStore(TeamStore);
  20. * ```
  21. */
  22. export function useLegacyStore<T extends LegacyStoreShape>(
  23. store: T
  24. ): ReturnType<T['getState']> {
  25. const [state, setState] = useState(store.getState());
  26. // Not all stores emit the new state, call get on change
  27. const callback = () => window._legacyStoreHookUpdate(() => setState(store.getState()));
  28. useEffect(() => store.listen(callback, undefined) as () => void, []);
  29. return state;
  30. }