setup useInfinitQuery for notifications

This commit is contained in:
Nouman Tahir 2022-09-22 17:50:53 +05:00
parent efb620540c
commit d5a0e3aa06
2 changed files with 56 additions and 102 deletions

View File

@ -1,32 +1,25 @@
import { useQuery } from "@tanstack/react-query";
import { useInfiniteQuery } from "@tanstack/react-query";
import { getNotifications } from "../ecency/ecency";
import { NotificationFilters } from "../ecency/ecency.types";
import QUERIES from "./queryKeys";
export const useNotificationsQuery = ( filter : NotificationFilters) => {
return useQuery([QUERIES.NOTIFICATIONS.GET, filter], async () => {
const resonse = getNotifications({ filter, since: undefined, limit: 20 })
return resonse || []
// const lastId = res.length > 0 ? [...res].pop().id : null;
// if (loadMore && (lastId === lastNotificationId || res.length === 0)) {
// setEndOfNotification(true);
// setIsRefershing(false);
// setIsLoading(false);
// } else {
// console.log('');
// const stateNotifications = notificationsMap.get(type) || [];
// const _notifications = loadMore
// ? unionBy(stateNotifications, res, 'id')
// : loadUnread
// ? unionBy(res, stateNotifications, 'id')
// : res;
// notificationsMap.set(type, _notifications);
// setNotificationsMap(notificationsMap);
// setLastNotificationId(lastId);
// setIsRefershing(false);
// setIsLoading(false);
// }
export const useNotificationsQuery = (filter: NotificationFilters) => {
const _fetchLimit = 20
return useInfiniteQuery<any[]>([QUERIES.NOTIFICATIONS.GET, filter], async ({ pageParam }) => {
console.log("fetching page since:", pageParam)
const response = getNotifications({ filter, since: pageParam, limit: _fetchLimit })
console.log("new page fetched", response)
return response || []
}, {
initialData: {
pageParams: [undefined],
pages: []
},
getNextPageParam: (lastPage) => {
const lastId = lastPage.length === _fetchLimit ? lastPage.lastItem.id : undefined;
console.log("extracting next page parameter", lastId);
return lastId;
}
});
}

View File

@ -1,14 +1,13 @@
/* eslint-disable react/no-unused-state */
import React, { useRef, useState } from 'react';
import { Alert, Button } from 'react-native';
import React, { useMemo, useRef, useState } from 'react';
import { Alert } from 'react-native';
import { useDispatch } from 'react-redux';
import get from 'lodash/get';
import { useIntl } from 'react-intl';
// Actions and Services
import { unionBy } from 'lodash';
import { useEffect } from 'react';
import { getNotifications, markNotifications } from '../../../providers/ecency/ecency';
import { markNotifications } from '../../../providers/ecency/ecency';
import { updateUnreadActivityCount } from '../../../redux/actions/accountAction';
// Constants
@ -22,9 +21,10 @@ import bugsnapInstance from '../../../config/bugsnag';
import { useAppSelector } from '../../../hooks';
import { useNotificationsQuery } from '../../../providers/queries';
import { NotificationFilters } from '../../../providers/ecency/ecency.types';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useQueryClient } from '@tanstack/react-query';
import QUERIES from '../../../providers/queries/queryKeys';
import { SafeAreaView } from 'react-native-safe-area-context';
const NotificationContainer = ({ navigation }) => {
const intl = useIntl();
@ -39,27 +39,21 @@ const NotificationContainer = ({ navigation }) => {
const unreadCountRef = useRef(currentAccount.unread_acitivity_count || 0);
const [notificationsMap, setNotificationsMap] = useState(new Map());
const [lastNotificationId, setLastNotificationId] = useState(null);
const [isRefreshing, setIsRefershing] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [selectedFilter, setSelectedFilter] = useState<NotificationFilters>(NotificationFilters.ACTIVITIES);
const [endOfNotification, setEndOfNotification] = useState(false);
const notificationsQuery = useNotificationsQuery(selectedFilter)
useEffect(() => {
setEndOfNotification(false);
setNotificationsMap(new Map());
// _getActivities(selectedFilter);
notificationsQuery.refetch();
//TODO: later invalidate all queries on logout or account switch using query client
queryClient.refetchQueries([QUERIES.NOTIFICATIONS.GET]);
}, [currentAccount.username]);
useEffect(() => {
if (currentAccount.unread_activity_count > unreadCountRef.current) {
queryClient.refetchQueries([QUERIES.NOTIFICATIONS.GET]); //refetches all cahced quries starting with given ke
//TODO: handle new notification received, either invalidate filters or add data above
queryClient.refetchQueries([QUERIES.NOTIFICATIONS.GET], {
refetchPage: (page, index) => index === 0
});
}
unreadCountRef.current = currentAccount.unread_activity_count;
}, [currentAccount.unread_activity_count]);
@ -67,52 +61,14 @@ const NotificationContainer = ({ navigation }) => {
const _getActivities = (loadMore = false, loadUnread = false) => {
if(loadMore){
console.log("load more notifications")
} else {
notificationsQuery.refetch();
}
// const since = loadMore ? lastNotificationId : null;
// if (isLoading) {
// return;
// }
// if (!endOfNotification || !loadMore || loadUnread) {
// setIsLoading(true);
// setIsRefershing(!loadMore);
// getNotifications({ filter: type, since: since, limit: 20 })
// .then((res) => {
// const lastId = res.length > 0 ? [...res].pop().id : null;
// if (loadMore && (lastId === lastNotificationId || res.length === 0)) {
// setEndOfNotification(true);
// setIsRefershing(false);
// setIsLoading(false);
// } else {
// console.log('');
// const stateNotifications = notificationsMap.get(type) || [];
// const _notifications = loadMore
// ? unionBy(stateNotifications, res, 'id')
// : loadUnread
// ? unionBy(res, stateNotifications, 'id')
// : res;
// notificationsMap.set(type, _notifications);
// setNotificationsMap(notificationsMap);
// setLastNotificationId(lastId);
// setIsRefershing(false);
// setIsLoading(false);
// }
// })
// .catch(() => {
// setIsRefershing(false);
// setIsLoading(false);
// });
// }
const _getActivities = (loadMore = false) => {
if (loadMore) {
console.log("load more notifications")
notificationsQuery.fetchNextPage();
} else {
console.log("refetching all")
notificationsQuery.refetch();
}
};
@ -166,19 +122,21 @@ const NotificationContainer = ({ navigation }) => {
dispatch(showProfileModal(username));
};
//TODO: handle mark as read mutations
const _readAllNotification = () => {
if (!isConnected) {
return;
}
setIsRefershing(true);
// setIsRefershing(true);
markNotifications()
.then(() => {
notificationsMap.forEach((notifications, key) => {
const updatedNotifications = notifications.map((item) => ({ ...item, read: 1 }));
notificationsMap.set(key, updatedNotifications);
});
// notificationsMap.forEach((notifications, key) => {
// const updatedNotifications = notifications.map((item) => ({ ...item, read: 1 }));
// notificationsMap.set(key, updatedNotifications);
// });
dispatch(updateUnreadActivityCount(0));
markHiveNotifications(currentAccount, pinCode)
@ -189,8 +147,8 @@ const NotificationContainer = ({ navigation }) => {
bugsnapInstance.notify(err);
});
setNotificationsMap(notificationsMap);
setIsRefershing(false);
// setNotificationsMap(notificationsMap);
// setIsRefershing(false);
})
.catch(() => {
Alert.alert(
@ -198,7 +156,7 @@ const NotificationContainer = ({ navigation }) => {
intl.formatMessage({ d: 'alert.unknow_error' }),
);
setIsRefershing(false);
// setIsRefershing(false);
});
};
@ -208,23 +166,26 @@ const NotificationContainer = ({ navigation }) => {
const _changeSelectedFilter = async (value) => {
setSelectedFilter(value);
setEndOfNotification(false);
};
const _notifications = notificationsQuery.data || [];
const _notifications = useMemo(() =>
notificationsQuery.data?.pages?.reduce(
(prevData, curData) => prevData.concat(curData), []
), [notificationsQuery.data?.pages]);
return (
<NotificationScreen
<NotificationScreen
getActivities={_getActivities}
notifications={_notifications}
navigateToNotificationRoute={_navigateToNotificationRoute}
handleOnUserPress={_handleOnUserPress}
readAllNotification={_readAllNotification}
handleLoginPress={_handleOnPressLogin}
isNotificationRefreshing={isRefreshing}
isNotificationRefreshing={notificationsQuery.isFetching}
isLoggedIn={isLoggedIn}
changeSelectedFilter={_changeSelectedFilter}
globalProps={globalProps}
isLoading={isLoading}
isLoading={notificationsQuery.isFetchingNextPage}
/>
);
};