Created
August 31, 2019 05:14
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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