convex
Version:
Client for the Convex Cloud
51 lines (50 loc) • 1.46 kB
JavaScript
import { useEffect, useState } from "react";
export function useSubscription({
// (Synchronously) returns the current value of our subscription.
getCurrentValue,
// This function is passed an event handler to attach to the subscription.
// It should return an unsubscribe function that removes the handler.
subscribe
}) {
const [state, setState] = useState(() => ({
getCurrentValue,
subscribe,
value: getCurrentValue()
}));
let valueToReturn = state.value;
if (state.getCurrentValue !== getCurrentValue || state.subscribe !== subscribe) {
valueToReturn = getCurrentValue();
setState({
getCurrentValue,
subscribe,
value: valueToReturn
});
}
useEffect(() => {
let didUnsubscribe = false;
const checkForUpdates = () => {
if (didUnsubscribe) {
return;
}
setState((prevState) => {
if (prevState.getCurrentValue !== getCurrentValue || prevState.subscribe !== subscribe) {
return prevState;
}
const value = getCurrentValue();
if (prevState.value === value) {
return prevState;
}
return { ...prevState, value };
});
};
const unsubscribe = subscribe(checkForUpdates);
checkForUpdates();
return () => {
didUnsubscribe = true;
unsubscribe();
};
}, [getCurrentValue, subscribe]);
return valueToReturn;
}
//# sourceMappingURL=use_subscription.js.map
;