DEV Community

Discussion on: RxJS with React

Collapse
 
briunsilo profile image
Brian Pedersen

Great tutorial! The only thing I missed was TypeScript annotations. Here they are for any one else needing them.

// Creating a custom hook
function useObservable<T>(observable: Observable<T>) {
    const [state, setState] = useState<T>();

    useEffect(() => {
        const sub = observable.subscribe(setState);
        return () => sub.unsubscribe();
    }, [observable]);

    return state;
}
// ...
const names = useObservable<string[]>(names$);


// Fetching some data
const getName = (user: User) => `${user.name.first} ${user.name.last}`;

const names$ = ajax.getJSON<{ results: User[] }>(api).pipe(
    map(({ results: users }) => users.map(getName))
);
Enter fullscreen mode Exit fullscreen mode