Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: users lazy loading scroll #683

Merged
merged 1 commit into from
Dec 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion frontend/src/api/userService.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ export const getAllUsers = (context?: GetServerSidePropsContext): Promise<User[]
fetchData(`/users`, { context, serverSide: !!context });

export const getAllUsersWithTeams = (
pageParam: number,
context?: GetServerSidePropsContext,
): Promise<UserWithTeams[]> => fetchData(`/users/teams`, { context, serverSide: !!context });
): Promise<{ userWithTeams: UserWithTeams[]; hasNextPage: boolean; page: number }> =>
fetchData(`/users/teams?page=${pageParam ?? 0}`, { context, serverSide: !!context });

export const updateUserIsAdminRequest = (user: UpdateUserIsAdmin): Promise<User> =>
fetchData(`/users/sadmin/`, { method: 'PUT', data: user });
6 changes: 1 addition & 5 deletions frontend/src/components/Users/UsersList/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@ import React from 'react';

import ListOfCards from './partials/ListOfCards';

type UsersWithTeamsProps = {
isFetching: boolean;
};

const TeamsList = ({ isFetching }: UsersWithTeamsProps) => <ListOfCards isLoading={isFetching} />;
const TeamsList = () => <ListOfCards />;

export default TeamsList;
Original file line number Diff line number Diff line change
@@ -1,34 +1,90 @@
import React from 'react';
import React, { useMemo, useRef } from 'react';

import { DotsLoading } from '@/components/loadings/DotsLoading';
import Flex from '@/components/Primitives/Flex';
import { UserWithTeams } from '@/types/user/user';
import Text from '@/components/Primitives/Text';
import SearchInput from '@/components/Teams/CreateTeam/ListMembers/SearchInput';
import { useRecoilValue } from 'recoil';
import { usersWithTeamsState } from '@/store/user/atoms/user.atom';
import { useSetRecoilState } from 'recoil';
// import { usersWithTeamsState } from '@/store/user/atoms/user.atom';
RafaelSBatista97 marked this conversation as resolved.
Show resolved Hide resolved
import { useInfiniteQuery } from 'react-query';
import { getAllUsersWithTeams } from '@/api/userService';
import { ToastStateEnum } from '@/utils/enums/toast-types';
import { toastState } from '@/store/toast/atom/toast.atom';
import { ScrollableContent } from '../../../../Boards/MyBoards/styles';
import CardBody from '../CardUser/CardBody';

type ListOfCardsProp = {
isLoading: boolean;
};
const ListOfCards = React.memo(() => {
const setToastState = useSetRecoilState(toastState);
// const setUsersWithTeamsState = useSetRecoilState(usersWithTeamsState);
RafaelSBatista97 marked this conversation as resolved.
Show resolved Hide resolved
const scrollRef = useRef<HTMLDivElement>(null);

const fetchUsers = useInfiniteQuery(
'usersWithTeams',
({ pageParam = 0 }) => getAllUsersWithTeams(pageParam),
{
enabled: true,
refetchOnWindowFocus: false,
getNextPageParam: (lastPage) => {
const { hasNextPage, page } = lastPage;
if (hasNextPage) return page + 1;
return undefined;
},
onError: () => {
setToastState({
open: true,
content: 'Error getting the users',
type: ToastStateEnum.ERROR,
});
},
},
);

const { data, isLoading } = fetchUsers;

// if (data) {
// setUsersWithTeamsState(data?.pages[0].userWithTeams);
// }
RafaelSBatista97 marked this conversation as resolved.
Show resolved Hide resolved

const users = useMemo(() => {
const usersArray: UserWithTeams[] = [];
data?.pages.forEach((page) => {
page.userWithTeams?.forEach((user) => {
usersArray.push(user);
});
});
return usersArray;
}, [data?.pages]);

const onScroll = () => {
if (scrollRef.current) {
const { scrollTop, scrollHeight, clientHeight } = scrollRef.current;
if (scrollTop + clientHeight + 2 >= scrollHeight && fetchUsers.hasNextPage) {
fetchUsers.fetchNextPage();
}
}
};

const ListOfCards = React.memo<ListOfCardsProp>(({ isLoading }) => {
const usersWithTeams = useRecoilValue(usersWithTeamsState);
return (
<>
<Flex>
<Text css={{ fontWeight: '$bold', flex: 1, mt: '$36' }}>
{usersWithTeams.length} registered users
{users.length} registered users
</Text>
<Flex css={{ width: '460px' }} direction="column" gap={16}>
<SearchInput icon="search" iconPosition="left" id="search" placeholder="Search user" />
</Flex>
</Flex>
<ScrollableContent direction="column" gap="24" justify="start" css={{ mt: '-1px' }}>
<ScrollableContent
direction="column"
gap="24"
justify="start"
css={{ mt: '$24', height: 'calc(100vh - 350px)', overflow: 'auto', pr: '$10' }}
ref={scrollRef}
onScroll={onScroll}
>
<Flex direction="column">
{usersWithTeams?.map((user: UserWithTeams) => (
{users.map((user: UserWithTeams) => (
<CardBody key={user.user._id} userWithTeams={user} />
))}
</Flex>
Expand Down
14 changes: 7 additions & 7 deletions frontend/src/hooks/useUser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { updateUserIsAdminRequest } from '../api/userService';
import useUserUtils from './useUserUtils';

const useUser = (): UseUserType => {
const { setToastState, usersWithTeamsList, setUsersWithTeamsList, queryClient } = useUserUtils();
const { setToastState, queryClient } = useUserUtils();

const resetToken = useMutation<ResetTokenResponse, AxiosError, EmailUser>(
(emailUser: EmailUser) => resetTokenEmail(emailUser),
Expand All @@ -43,15 +43,15 @@ const useUser = (): UseUserType => {
};

const updateUserIsAdmin = useMutation(updateUserIsAdminRequest, {
onSuccess: (data) => {
onSuccess: () => {
queryClient.invalidateQueries('usersWithTeams');

// updates the usersList recoil
const users = usersWithTeamsList.map((user) =>
user.user._id === data._id ? { ...user, isAdmin: data.isSAdmin } : user,
);
// // updates the usersList recoil
// const users = usersWithTeamsList.map((user) =>
// user.user._id === data._id ? { ...user, isAdmin: data.isSAdmin } : user,
// );
RafaelSBatista97 marked this conversation as resolved.
Show resolved Hide resolved

setUsersWithTeamsList(users);
// setUsersWithTeamsList(users);
RafaelSBatista97 marked this conversation as resolved.
Show resolved Hide resolved

setToastState({
open: true,
Expand Down
42 changes: 2 additions & 40 deletions frontend/src/pages/users/index.tsx
Original file line number Diff line number Diff line change
@@ -1,47 +1,22 @@
import { ReactElement, Suspense } from 'react';
import { dehydrate, QueryClient, useQuery } from 'react-query';
import { GetServerSideProps, GetServerSidePropsContext } from 'next';
import { useSession } from 'next-auth/react';
import { useSetRecoilState } from 'recoil';

import QueryError from '@/components/Errors/QueryError';
import Layout from '@/components/layouts/Layout';
import LoadingPage from '@/components/loadings/LoadingPage';
import Flex from '@/components/Primitives/Flex';
import UsersList from '@/components/Users/UsersList';
import { getAllUsersWithTeams } from '../../api/userService';
import requireAuthentication from '../../components/HOC/requireAuthentication';
import { toastState } from '../../store/toast/atom/toast.atom';
import { usersWithTeamsState } from '../../store/user/atoms/user.atom';
import { ToastStateEnum } from '../../utils/enums/toast-types';

const Users = () => {
const { data: session } = useSession({ required: true });
const setToastState = useSetRecoilState(toastState);
const setUsersWithTeamsState = useSetRecoilState(usersWithTeamsState);

const { data, isFetching } = useQuery(['usersWithTeams'], () => getAllUsersWithTeams(), {
enabled: false,
refetchOnWindowFocus: false,
onError: () => {
setToastState({
open: true,
content: 'Error getting the users',
type: ToastStateEnum.ERROR,
});
},
});

if (data) {
setUsersWithTeamsState(data);
}
if (!session || !data) return null;
if (!session) return null;

return (
<Flex direction="column">
<Suspense fallback={<LoadingPage />}>
<QueryError>
<UsersList isFetching={isFetching} />
<UsersList />
</QueryError>
</Suspense>
</Flex>
Expand All @@ -51,16 +26,3 @@ const Users = () => {
Users.getLayout = (page: ReactElement) => <Layout>{page}</Layout>;

export default Users;

export const getServerSideProps: GetServerSideProps = requireAuthentication(
async (context: GetServerSidePropsContext) => {
const queryClient = new QueryClient();
await queryClient.prefetchQuery('usersWithTeams', () => getAllUsersWithTeams(context));

return {
props: {
dehydratedState: JSON.parse(JSON.stringify(dehydrate(queryClient))),
},
};
},
);