React Hook useSubject

Date: 2022-12-13
/* eslint-disable react-hooks/exhaustive-deps */
import { useEffect, useState } from "react";
import { Subject } from "rxjs";
function useSubject<T>(subject: Subject<T| undefined>, initialValue?: T) : [T | undefined, (val : T | undefined)=> any] {
    const [data, setData] = useState<T | undefined>(initialValue);
    useEffect(() => {
        if (!subject) { return; }
        const subscription = subject.subscribe(x => {
            setData(x);
        });
        return () => subscription.unsubscribe();
    }, [subject]);
    function updateData(val : T| undefined) {
        subject.next(val);
    }
    return [data, updateData];
}
export default useSubject;
70830cookie-checkReact Hook useSubject