Skip to content

Commit

Permalink
Create trip update mutation and custom hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
kanatagu committed Jan 30, 2024
1 parent 0cbf271 commit 7f8142f
Show file tree
Hide file tree
Showing 13 changed files with 499 additions and 198 deletions.
3 changes: 0 additions & 3 deletions app/trip/[id]/edit/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,6 @@ export default function TripEditPage({ params }: { params: { id: string } }) {
if ((!tripData && !tripLoading) || (!tagsData && !tagsLoading))
throw new Error('No trip data found')

console.log('tripDataCollection', tripDataCollection)
console.log('tagsData', tagsData)

return (
<>
<Header />
Expand Down
83 changes: 10 additions & 73 deletions app/trip/components/tag-form-modal.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { KeyboardEvent } from 'react'
import { useForm } from 'react-hook-form'
import {
Modal,
ModalOverlay,
Expand All @@ -13,15 +11,12 @@ import {
Tag,
useColorModeValue,
Box,
Heading,
useToast
Heading
} from '@chakra-ui/react'
import { FiPlusCircle, FiX } from 'react-icons/fi'
import { InputIconButton } from '@/components/input'
import { Loading } from '@/components/loading'
import { useUserId } from '@/providers/session-provider'
import { TagSchema, tagSchemaResolver } from '../schema'
import { useCreateTagMutation, useDeleteTagMutation } from '@generated/api'
import { useTagCreateDelete } from '../hooks'

type TagFormModalProps = {
isOpen: boolean
Expand All @@ -37,74 +32,16 @@ export const TagFormModal = ({
tagsCollectionRefetch
}: TagFormModalProps) => {
const tagBgColor = useColorModeValue('primary.700', 'primary.800')
const userId = useUserId()
const toast = useToast()

const {
addEnterHandler,
addTag,
deleteTag,
isCreating,
isDeleting,
register,
handleSubmit,
reset,
formState: { errors }
} = useForm<TagSchema>({
resolver: tagSchemaResolver
})

const [createTagMutation, { loading: isCreating }] = useCreateTagMutation()
const [deleteTagMutation, { loading: isDeleting }] = useDeleteTagMutation()

const addTag = async (input: TagSchema) => {
try {

await createTagMutation({
variables: {
name: input.name,
userId: userId
}
})
reset()
tagsCollectionRefetch()
} catch (error) {
console.error(error)
toast({
title: "We're sorry, but you failed to create a tag",
description:
error instanceof Error ? error.message : 'Please try again later.',
status: 'error',
duration: 5000,
isClosable: true,
position: 'top'
})
}
}

const addEnterHandler = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
e.preventDefault()
handleSubmit(addTag)()
}
}

const deleteTag = async (id: string) => {
try {
await deleteTagMutation({
variables: {
id: id
}
})
tagsCollectionRefetch()
} catch (error) {
console.error(error)
toast({
title: "We're sorry, but you failed to delete a tag",
description:
error instanceof Error ? error.message : 'Please try again later.',
status: 'error',
duration: 5000,
isClosable: true,
position: 'top'
})
}
}
errors
} = useTagCreateDelete(tagsCollectionRefetch)

return (
<Modal isOpen={isOpen} onClose={onClose} isCentered>
Expand Down Expand Up @@ -163,7 +100,7 @@ export const TagFormModal = ({
icon={FiPlusCircle}
isDisabled={isCreating}
onKeyDown={(e) => addEnterHandler(e)}
onClick={handleSubmit((d) => addTag(d))}
onClick={addTag}
{...register('name')}
/>
<FormErrorMessage>{errors?.name?.message}</FormErrorMessage>
Expand Down
149 changes: 37 additions & 112 deletions app/trip/components/trip-form.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { useForm, Controller } from 'react-hook-form'
import {
FormControl,
FormLabel,
Expand All @@ -11,43 +10,44 @@ import {
Flex,
Checkbox,
Box,
useDisclosure,
useToast
useDisclosure
} from '@chakra-ui/react'
import { PrimaryButton, SecondaryButton } from '@/components/button'
import { CustomDatePicker } from '@/components/date'
import { InputForm } from '@/components/input'
import { Loading } from '@/components/loading'
import { getDateObj, formatToISODate } from '@/libs/utils'

import { TagFormModal } from '../components'
import { tripSchemaResolver, TripSchema } from '../schema'
import {
useCreateTripTagMutation,
useDeleteTripTagMutation
} from '@generated/api'
import { useTripUpdate, useTripTagCreateDelete } from '../hooks'

export type TripDetailsArgs = {
id: string
image: string | null | undefined
title: string
dateFrom: string
dateTo: string | null | undefined
cost: string | null | undefined
costUnit: string | null | undefined
refetch: () => void
refetchLoading: boolean
}

export type TagsArgs = {
data: { id: string; name: string }[]
refetch: () => void
refetchLoading: boolean
}

export type TripTagsArgs = {
data: { id: string; tag_id: string; trip_id: string }[]
refetch: () => void
refetchLoading: boolean
}

type TripFormProps = {
tripDetails: {
id: string
image: string | null | undefined
title: string
dateFrom: string
dateTo: string | null | undefined
cost: number | null | undefined
costUnit: string | null | undefined
refetch: () => void
refetchLoading: boolean
}
tags: {
data: { id: string; name: string }[]
refetch: () => void
refetchLoading: boolean
}
tripTags: {
data: { id: string; tag_id: string; trip_id: string }[]
refetch: () => void
refetchLoading: boolean
}
tripDetails: TripDetailsArgs
tags: TagsArgs
tripTags: TripTagsArgs
}

export const TripForm = ({ tripDetails, tags, tripTags }: TripFormProps) => {
Expand All @@ -56,92 +56,16 @@ export const TripForm = ({ tripDetails, tags, tripTags }: TripFormProps) => {
'/images/no_image_dark.jpg'
)
const { isOpen, onOpen, onClose } = useDisclosure()
const toast = useToast()

console.log('tripTagsData', tripTags.data)

const [createTripTagMutation, { loading: isTripTagCreating }] =
useCreateTripTagMutation()
const [deleteTripTagMutation, { loading: isTripTagDeleting }] =
useDeleteTripTagMutation()

const {
register,
handleSubmit,
control,
formState: { errors }
} = useForm<TripSchema>({
defaultValues: {
title: tripDetails.title,
date_from: getDateObj(tripDetails.dateFrom),
date_to: tripDetails.dateTo ? getDateObj(tripDetails.dateTo) : null,
image_storage_object_id: tripDetails.image,
cost: tripDetails.cost ? tripDetails.cost.toString() : '',
cost_unit: tripDetails.costUnit
},
resolver: tripSchemaResolver
})

console.log('errors', errors)

const tagClickHandler = async (selectedTagId: string) => {
try {
const isTagIdAlreadyExists = tripTags.data.find(
(tripTag) => tripTag.tag_id === selectedTagId
)

if (isTagIdAlreadyExists) {
await deleteTripTagMutation({
variables: {
id: isTagIdAlreadyExists.id
}
})
tripTags.refetch()
return
}

if (!isTagIdAlreadyExists) {
await createTripTagMutation({
variables: {
tripId: tripDetails.id,
tagId: selectedTagId
}
})
tripTags.refetch()
}
} catch (error) {
console.error(error)
toast({
title: "We're sorry, but you failed to update a tag",
description:
error instanceof Error ? error.message : 'Please try again later.',
status: 'error',
duration: 5000,
isClosable: true,
position: 'top'
})
}
}

const updateTrip = async (data: TripSchema) => {
console.log('submit!', {
tripId: tripDetails.id,
data
})
const { onMutate, isTripUpdating, register, control, errors, Controller } =
useTripUpdate(tripDetails)

if (data.date_to) {
const dateTo = formatToISODate(data.date_to)
console.log('dateTo', dateTo)
}
}
const { tagClickHandler, isTripTagCreating, isTripTagDeleting } =
useTripTagCreateDelete(tripTags, tripDetails.id)

return (
<>
<VStack
as="form"
gap={{ base: '30px', md: '40px' }}
onSubmit={handleSubmit(updateTrip)}
>
<VStack as="form" gap={{ base: '30px', md: '40px' }} onSubmit={onMutate}>
<FormControl isInvalid={!!errors.title}>
<FormLabel>Title</FormLabel>
<InputForm
Expand Down Expand Up @@ -187,6 +111,7 @@ export const TripForm = ({ tripDetails, tags, tripTags }: TripFormProps) => {
<FormErrorMessage>{errors?.date_to?.message}</FormErrorMessage>
</FormControl>

{/* TODO Image Upload to storage & Send the URL string to DB */}
<FormControl isInvalid={!!errors.image_storage_object_id}>
<FormLabel>Image</FormLabel>
<HStack gap={{ base: '20px', md: '34px' }}>
Expand Down Expand Up @@ -253,7 +178,7 @@ export const TripForm = ({ tripDetails, tags, tripTags }: TripFormProps) => {
</FormControl>
</Flex>

<PrimaryButton size="lg" type="submit">
<PrimaryButton size="lg" type="submit" isDisabled={isTripUpdating}>
Save Trip
</PrimaryButton>
</VStack>
Expand Down
8 changes: 8 additions & 0 deletions app/trip/graphql/mutation/updateTrip.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
mutation updateTrip($id: UUID!, $set: tripsUpdateInput!) {
updatetripsCollection(set: $set, filter: { id: { eq: $id } }) {
records {
id
title
}
}
}
3 changes: 3 additions & 0 deletions app/trip/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { useTagCreateDelete } from './useTagCreateDelete'
export { useTripTagCreateDelete } from './useTripTagCreateDelete'
export { useTripUpdate } from './useTripUpdate'
Loading

0 comments on commit 7f8142f

Please sign in to comment.