Is there a way to retrieve reference for unsubscribing from a ThunkAction like the following:
export const fetchSomeData = () => async (dispatch: Dispatch, getState: GetState) => {
let unsubscribeUserAuth: UnsubscribeUserAuth | null = null;
let unsubscribeDataSnapshot: UnsubscribeDataSnapshot | null = null;
try {
// Subscribe to user authentication state changes
unsubscribeUserAuth = getAuth().onAuthStateChanged(user => {
// check if user is authenticated
});
// Subscribe to data snapshot updates
unsubscribeDataSnapshot = onSnapshot(queryRef, (docsSnapshot) => {
// dispatches payload data and sets loaded to true
})
return {
unsubscribe: () => {
if (unsubscribeUserAuth && unsubscribeDataSnapshot) {
unsubscribeUserAuth();
unsubscribeDataSnapshot();
}
}
}
catch(error) {
// dispatches error and sets error flag to true
if (unsubscribeUserAuth && unsubscribeDataSnapshot) {
unsubscribeUserAuth();
unsubscribeDataSnapshot();
}
}
}
I am attempting to execute this from a React useEffect
const { loaded } = useSelector(state => ({
loaded: state.fireReducer.loaded,
}))
const { fetchSomeData } = useActions({
fetchSomeData: fireActions.fetchSomeData,
});
useEffect(() => {
let actionReference;
if (!loaded) {
actionReference = fetchSomeData();
}
return () => {
actionReference.unsubscribe();
}
}, [loaded])