Skip to content

Commit

Permalink
feat: you can now edit the name of the collection and other enhancements
Browse files Browse the repository at this point in the history
  • Loading branch information
Franqsanz committed Nov 14, 2024
1 parent 8084c74 commit cab3431
Show file tree
Hide file tree
Showing 8 changed files with 207 additions and 23 deletions.
74 changes: 64 additions & 10 deletions src/components/modals/ModalCollection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,44 +14,98 @@ import {
ModalOverlay,
useColorModeValue,
} from '@chakra-ui/react';
import { FaCheckCircle } from 'react-icons/fa';

import { useCreateCollections } from '@hooks/queries';
import { useCreateCollections, useUpdateCollectionName } from '@hooks/queries';
import { useAuth } from '@contexts/AuthContext';
import { DisclosureType } from '@components/types';
import { useMyToast } from '@hooks/useMyToast';

interface ModalCollectionType extends DisclosureType {
title: string;
textButton: string;
nameCollection?: string;
collectionId?: string; // Añade el ID de la colección
isEditing?: boolean; // Añade un flag para saber si estamos editando
refetch: () => void;
}

export function ModalCollection({ isOpen, onClose, refetch }: ModalCollectionType) {
export function ModalCollection({
title,
textButton,
nameCollection,
collectionId,
isEditing = false,
isOpen,
onClose,
refetch,
}: ModalCollectionType) {
const [name, setName] = useState<string>('');
const bgColorBox = useColorModeValue('white', 'gray.900');
const bgColorInput = useColorModeValue('gray.100', 'gray.800');
const { currentUser } = useAuth();
const uid = currentUser?.uid;
const navigate = useNavigate();
const { mutate, isPending, isSuccess } = useCreateCollections(uid);
const myToast = useMyToast();

// Añade el mutation para actualizar
const updateMutation = useUpdateCollectionName(uid, collectionId);
const createMutation = useCreateCollections(uid);

// Usa la mutation correspondiente según isEditing
const { mutate, isPending, isSuccess } = isEditing
? updateMutation
: createMutation;

// Carga el nombre inicial si estamos editando
useEffect(() => {
if (isEditing && nameCollection) {
setName(nameCollection);
}
}, [isEditing, nameCollection]);

useEffect(() => {
if (isSuccess) {
onClose();
refetch();
setName('');
navigate('/my-collections');

// Solo navega a /my-collections si estamos creando
if (!isEditing) {
navigate('/my-collections');
}

myToast({
title: isEditing
? 'Se actualizó la colección.'
: 'Se creó una nueva colección.',
icon: FaCheckCircle,
iconColor: 'green.700',
bgColor: 'black',
width: '200px',
color: 'whitesmoke',
align: 'center',
padding: '1',
fntSize: 'md',
bxSize: 5,
});
}
}, [isSuccess, navigate, onClose]);
}, [isSuccess, navigate, onClose, isEditing]);

function handleNameCollection(e: React.ChangeEvent<HTMLInputElement>) {
const { value } = e.target;

setName(value);
}

function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();

if (!isPending) {
mutate(name);
if (isEditing && collectionId) {
mutate(name);

Check failure on line 105 in src/components/modals/ModalCollection.tsx

View workflow job for this annotation

GitHub Actions / check-test (20.x)

Type '[]' has no properties in common with type 'MutateOptions<any, Error, string | undefined, unknown> & MutateOptions<any, Error, string, unknown>'.
} else {
mutate(name);

Check failure on line 107 in src/components/modals/ModalCollection.tsx

View workflow job for this annotation

GitHub Actions / check-test (20.x)

Type '[]' has no properties in common with type 'MutateOptions<any, Error, string | undefined, unknown> & MutateOptions<any, Error, string, unknown>'.
}
}
}

Expand All @@ -60,7 +114,7 @@ export function ModalCollection({ isOpen, onClose, refetch }: ModalCollectionTyp
<Modal isOpen={isOpen} onClose={onClose} size={{ base: 'xs', sm: 'md' }}>
<ModalOverlay backdropFilter='blur(7px)' />
<ModalContent overflow='hidden'>
<ModalHeader bg={bgColorBox}>Crear nueva colección</ModalHeader>
<ModalHeader bg={bgColorBox}>{title}</ModalHeader>
<ModalCloseButton />
<ModalBody bg={bgColorBox}>
<form onSubmit={handleSubmit}>
Expand All @@ -87,10 +141,10 @@ export function ModalCollection({ isOpen, onClose, refetch }: ModalCollectionTyp
rounded='lg'
isDisabled={!name || isPending}
isLoading={isPending}
loadingText='Creando...'
loadingText={isEditing ? 'Actualizando...' : 'Creando...'}
_hover={{ outline: 'none', bg: 'green.600' }}
>
Crear
{textButton}
</Button>
</Flex>
</form>
Expand Down
57 changes: 57 additions & 0 deletions src/components/profile/collections/MenuCollections.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import React, { useEffect } from 'react';
import { Menu, MenuButton, MenuList, MenuItem, IconButton } from '@chakra-ui/react';
import { FiMoreVertical } from 'react-icons/fi';
import { FaCheckCircle } from 'react-icons/fa';

import { useDeleteCollections } from '@hooks/queries';
import { useAuth } from '@contexts/AuthContext';
import { useMyToast } from '@hooks/useMyToast';

export function MenuCollections({ id, name, refetch }: any) {
const { currentUser } = useAuth();
const uid = currentUser?.uid;
const myToast = useMyToast();
const { mutate, isSuccess } = useDeleteCollections();

useEffect(() => {
if (isSuccess) {
refetch();
myToast({
title: `Se elimino la colección ${name}.`,
icon: FaCheckCircle,
iconColor: 'green.700',
bgColor: 'black',
width: '200px',
color: 'whitesmoke',
align: 'center',
padding: '1',
fntSize: 'md',
bxSize: 5,
});
}
}, [isSuccess]);

function deleteCollection(id: string) {
mutate([uid, id]);
}

return (
<>
<Menu>
<MenuButton
as={IconButton}
aria-label='Options'
icon={<FiMoreVertical />}
bg='transparent'
_hover={{ bg: 'transparent' }}
_active={{ bg: 'transparent' }}
/>
<MenuList p='0' fontSize='sm'>
<MenuItem p='2' onClick={() => deleteCollection(id)}>
Eliminar colección
</MenuItem>
</MenuList>
</Menu>
</>
);
}
12 changes: 12 additions & 0 deletions src/hooks/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
getFindOneCollection,
deleteCollections,
postCollections,
patchCollectionsName,
} from '@services/api';
import { useAccountActions } from '@hooks/useAccountActions';
import { keys } from '@utils/utils';
Expand Down Expand Up @@ -286,6 +287,16 @@ function useCreateCollections(userId: string | undefined) {
});
}

function useUpdateCollectionName(
userId: string | undefined,
collectionId: string | undefined,
) {
return useMutation({
mutationKey: [keys.updateCollectionsName],
mutationFn: (name: string) => patchCollectionsName(userId, collectionId, name),
});
}

function useCollections(userId: string | undefined) {
return useQuery({
queryKey: [keys.allCollections],
Expand Down Expand Up @@ -368,6 +379,7 @@ export {
useCollections,
useCollectionDetail,
useCreateCollections,
useUpdateCollectionName,
useDeleteCollections,

// Usuarios
Expand Down
24 changes: 17 additions & 7 deletions src/pages/profile/collections/AllCollections.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,22 @@ import { collections } from '@assets/assets';
import { MyContainer } from '@components/ui/MyContainer';
import { MySimpleGrid } from '@components/ui/MySimpleGrid';
import { ModalCollection } from '@components/modals/ModalCollection';
import { SkeletonACollections } from '@components/skeletons/SkeletonACollections';
import { useCollections } from '@hooks/queries';
import { useAuth } from '@contexts/AuthContext';
import { parseDate } from '@utils/utils';
import { SkeletonACollections } from '@components/skeletons/SkeletonACollections';
import { MenuCollections } from '@components/profile/collections/MenuCollections';

export function AllCollections() {
const bgColorButton = useColorModeValue('green.500', 'green.700');
const grayColor = useColorModeValue('#E2E8F0', '#2D3748');
const { isOpen, onOpen, onClose } = useDisclosure();
const { currentUser } = useAuth();
const uid = currentUser?.uid;
const { data, refetch, isPending: isPendingData } = useCollections(uid);
const { data, refetch, isPending } = useCollections(uid);
let collectionsUI;

if (isPendingData) {
if (isPending) {
return <SkeletonACollections />;
}

Expand Down Expand Up @@ -80,7 +81,7 @@ export function AllCollections() {
to={`/my-collections/${id}`}
tabIndex={-1}
_hover={{ outline: 'none' }}
> */}
> */}
<Flex
w={{ base: '127px', sm: '160px', md: '250px' }}
h={{ base: '200px', sm: '210px' }}
Expand All @@ -92,6 +93,9 @@ export function AllCollections() {
justify='center'
position='relative'
>
<Flex w='full' justify='flex-end'>
<MenuCollections id={id} name={name} refetch={refetch} />
</Flex>
<Flex
direction='column'
mb='3'
Expand All @@ -111,9 +115,9 @@ export function AllCollections() {
h='30px'
px='0'
m='auto'
fontSize='xs'
size='xs'
as={NavLink}
to={`/my-collections/${id}`}
to={`/my-collections/collection/${id}`}
fontWeight='normal'
_hover={{ color: 'none' }}
>
Expand All @@ -133,7 +137,13 @@ export function AllCollections() {
<MainHead title='Mis colecciones | XBuniverse' />
<ContainerTitle title='Mis colecciones' />
<ScrollRestoration />
<ModalCollection isOpen={isOpen} onClose={onClose} refetch={refetch} />
<ModalCollection
title='Crear Colección'
textButton='Crear'
isOpen={isOpen}
onClose={onClose}
refetch={refetch}
/>
<Flex m='0 auto'>
<Flex
w={{ base: '1315px', '2xl': '1580px' }}
Expand Down
47 changes: 42 additions & 5 deletions src/pages/profile/collections/CollectionDetail.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import React, { useEffect } from 'react';
import { NavLink, useNavigate, useParams } from 'react-router-dom';
import { Box, Button, Flex, Icon, Image, Link } from '@chakra-ui/react';
import {
Box,
Button,
Flex,
Icon,
Image,
Link,
useDisclosure,
} from '@chakra-ui/react';

import { useCollectionDetail, useDeleteCollections } from '@hooks/queries';
import { MainHead } from '@components/layout/Head';
Expand All @@ -13,19 +21,40 @@ import { useAuth } from '@contexts/AuthContext';
import { MdOutlineExplore } from 'react-icons/md';
import { FiArrowLeft } from 'react-icons/fi';
import { SkeletonDCollection } from '@components/skeletons/SkeletonDCollection';
import { useMyToast } from '@hooks/useMyToast';
import { FaCheckCircle } from 'react-icons/fa';
import { ModalCollection } from '@components/modals/ModalCollection';

export function CollectionDetail() {
const { collectionId } = useParams();
const navigate = useNavigate();
const { currentUser } = useAuth();
const uid = currentUser?.uid;
const { data, isPending: isPendingData } = useCollectionDetail(collectionId);
const myToast = useMyToast();
const { isOpen, onOpen, onClose } = useDisclosure();
const {
data,
isPending: isPendingData,
refetch,
} = useCollectionDetail(collectionId);
const { mutate, isSuccess, isPending: isPendingDelete } = useDeleteCollections();
let asideAndCardsUI;

useEffect(() => {
if (isSuccess) {
navigate(`/my-collections`, { replace: true });
myToast({
title: `Se elimino la colección ${data?.name}.`,
icon: FaCheckCircle,
iconColor: 'green.700',
bgColor: 'black',
width: '200px',
color: 'whitesmoke',
align: 'center',
padding: '1',
fntSize: 'md',
bxSize: 5,
});
}
}, [isSuccess, navigate]);

Expand Down Expand Up @@ -115,6 +144,16 @@ export function CollectionDetail() {
<>
<MainHead title={`${data?.name} | Mis colecciones | XBuniverse`} />
<ContainerTitle title={data?.name} />
<ModalCollection
title='Editar Colección'
textButton='Guardar'
nameCollection={data?.name}
collectionId={collectionId}
isEditing={true}
isOpen={isOpen}
onClose={onClose}
refetch={refetch}
/>
<Flex m='0 auto'>
<Flex
w={{ base: '1315px', '2xl': '1580px' }}
Expand All @@ -132,11 +171,9 @@ export function CollectionDetail() {
</Button>
<Flex gap='3'>
<Button
// onClick={() => deleteCollection(data?.id)}
onClick={onOpen}
size='sm'
fontWeight='normal'
loadingText='Editando...'
isLoading={isPendingDelete}
_hover={{ color: 'none' }}
>
Editar nombre
Expand Down
2 changes: 1 addition & 1 deletion src/routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ export const routes = createBrowserRouter([
),
},
{
path: '/my-collections/:collectionId',
path: '/my-collections/collection/:collectionId',
element: (
<PrivateRoute>
<CollectionDetail />
Expand Down
Loading

0 comments on commit cab3431

Please sign in to comment.