Skip to content

Instantly share code, notes, and snippets.

@nartc
Created August 31, 2019 05:14
Show Gist options
  • Save nartc/5a426f94285b7e74cfb50a481d64e3c6 to your computer and use it in GitHub Desktop.
Save nartc/5a426f94285b7e74cfb50a481d64e3c6 to your computer and use it in GitHub Desktop.
Revision of Thomas Burleson's React Hooks + Facade article on Medium: https://medium.com/p/4e116330bbe1
export function useUsersFacade(): [
UserState,
typeof usersService.setActive,
typeof usersService.updateActive
] {
const [users, setUsers] = useState<User[]>([]);
const [active, setActive] = useState<User | null>(null);
/**
* Manage subscriptions with auto-cleanup
*/
useEffect(() => {
const subscriptions: Subscription[] = [
onEmit<User[]>(usersQuery.users$, setUsers),
onEmit<User>(usersQuery.active$, setActive)
];
usersService.loadAll();
return () => {
subscriptions.map(it => it.unsubscribe());
};
}, []);
return [
{ users, active },
useCallback(usersService.setActive.bind(usersService), []),
useCallback(usersService.updateActive.bind(usersService), [])
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment