Skip to content

Commit

Permalink
create AcitivityUploadedFile record when upload activity image.
Browse files Browse the repository at this point in the history
  • Loading branch information
samuraikun committed Feb 18, 2024
1 parent ec5ace6 commit 43cdb4b
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 70 deletions.
11 changes: 4 additions & 7 deletions app/activity/[id]/edit/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,6 @@ export default function ActivityEditPage({
notifyOnNetworkStatusChange: true
})

const dummyUrls: string[] = [
'https://images.unsplash.com/photo-1612852098516-55d01c75769a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1yZWxhdGVkfDR8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=900&q=60',
'https://images.unsplash.com/photo-1627875764093-315831ac12f7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1yZWxhdGVkfDJ8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=900&q=60',
'https://images.unsplash.com/photo-1571432248690-7fd6980a1ae2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1yZWxhdGVkfDl8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=900&q=60'
]

const activityDataCollection =
activityData?.activityCollection?.edges[0]?.node
const activityDetailsRefetch = () => {
Expand Down Expand Up @@ -68,7 +62,10 @@ export default function ActivityEditPage({
memo: activityDataCollection?.memo,
cost: activityDataCollection?.cost,
costUnit: activityDataCollection?.cost_unit,
uploadedFileUrls: dummyUrls,
uploadedFileUrls:
activityDataCollection?.activity_uploaded_filesCollection?.edges.map(
(edge) => edge?.node?.file_url
),
refetch: activityDetailsRefetch,
refetchLoading: activityDetailsRefetchLoading
}}
Expand Down
15 changes: 4 additions & 11 deletions app/activity/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,12 @@ export default function ActivityDetails({
}
})

const dummyUrls: string[] = [
'https://images.unsplash.com/photo-1612852098516-55d01c75769a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1yZWxhdGVkfDR8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=900&q=60',
'https://images.unsplash.com/photo-1627875764093-315831ac12f7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1yZWxhdGVkfDJ8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=900&q=60',
'https://images.unsplash.com/photo-1571432248690-7fd6980a1ae2?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1yZWxhdGVkfDl8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=900&q=60'
]

if (!loading && !data) throw new Error('No activity data found')

const activityData = data?.activityCollection?.edges[0]?.node
const uploadedImageUrls = activityData?.activity_uploaded_filesCollection
? activityData?.activity_uploaded_filesCollection?.edges.map(
(edge) => edge?.node?.file_url || ''
(edge) => edge?.node?.file_url
)
: []

Expand All @@ -56,10 +50,9 @@ export default function ActivityDetails({
address={activityData?.address}
url={activityData?.url}
/>
{/* TODO: Fetch images from the database once available. */}
<Carousel
urls={uploadedImageUrls.length > 0 ? uploadedImageUrls : dummyUrls}
/>
{uploadedImageUrls.length > 0 && (
<Carousel urls={uploadedImageUrls} />
)}
<ActivityInfo memo={activityData?.memo} cost={activityData?.cost} />
<Box mt="60px" display="flex" alignItems="center">
<FiChevronLeft />
Expand Down
51 changes: 36 additions & 15 deletions app/activity/components/activity-form.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React, { useCallback, useState } from 'react'
import { useDropzone } from 'react-dropzone'
import { Controller, useForm } from 'react-hook-form'
import React, { useState } from 'react'
import { Controller, useForm, useWatch } from 'react-hook-form'
import {
Box,
FormControl,
Expand All @@ -11,7 +10,8 @@ import {
SimpleGrid,
Text,
Flex,
VStack
VStack,
Input
} from '@chakra-ui/react'
import { PrimaryButton } from '@/components/button'
import { CustomDateTimePicker } from '@/components/customDateTimePicker'
Expand Down Expand Up @@ -45,11 +45,7 @@ export const ActivityForm = ({
activityDetails
}: ActivityFormProps) => {
const [selectedImages, setSelectedImages] = useState<File[]>([])
const onDrop = useCallback((acceptedFiles: File[]) => {
setSelectedImages((prevImages) => [...prevImages, ...acceptedFiles])
}, [])
const { getRootProps, getInputProps } = useDropzone({ onDrop })
function removeImage(index: number) {
const removeImage = (index: number) => {
setSelectedImages((prevImages) => {
const newImages = [...prevImages]
newImages.splice(index, 1)
Expand Down Expand Up @@ -77,10 +73,11 @@ export const ActivityForm = ({
cost: activityDetails?.cost || undefined,
costUnit: activityDetails?.costUnit || undefined,
uploadedFileUrls: activityDetails?.uploadedFileUrls || undefined,
newFiles: selectedImages
newFiles: []
},
resolver: activityResolver
})
const newFiles = useWatch({ control, name: 'newFiles' })

const { createActivity, isActivityCreating } = useActivityCreate(tripId)
const { updateActivity, isActivityUpdating } = useActivityUpdate(tripId)
Expand Down Expand Up @@ -180,6 +177,7 @@ export const ActivityForm = ({
width={{ base: '160px', md: '180px' }}
height={{ base: '106px', md: '120px' }}
margin="auto"
_hover={{ cursor: 'pointer' }}
/>
))}
{selectedImages.map((image, index) => (
Expand All @@ -191,13 +189,13 @@ export const ActivityForm = ({
width={{ base: '160px', md: '180px' }}
height={{ base: '106px', md: '120px' }}
margin="auto"
_hover={{ cursor: 'pointer' }}
onClick={() => removeImage(index)}
/>
))}
</SimpleGrid>

<Box
{...getRootProps()}
textAlign="center"
mt={{
base: 0,
Expand All @@ -208,10 +206,33 @@ export const ActivityForm = ({
: '0'
}}
>
<PrimaryButton variant="outline">
<input {...getInputProps()} />
Add Image
</PrimaryButton>
<Controller
name="newFiles"
control={control}
render={({ field: { onChange } }) => (
<PrimaryButton variant="outline" as="label">
Add Image
<Input
type="file"
accept="image/*"
multiple
hidden
onChange={(event) => {
const files = event.target.files
if (files && newFiles) {
const newFileList = Array.from(files)
setSelectedImages((prevImages) => [
...prevImages,
...newFileList
])
newFiles.push(...newFileList)
onChange(newFiles)
}
}}
/>
</PrimaryButton>
)}
/>
</Box>

<FormControl isInvalid={!!errors.memo} mt={{ base: '30px', md: '40px' }}>
Expand Down
33 changes: 25 additions & 8 deletions app/activity/hooks/useUploadFiles.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { createClient } from '@supabase/supabase-js'
// import { useCreateActivityUploadedFilesMutation } from '@generated/api'
import { useCreateActivityUploadedFilesMutation } from '@generated/api'

export const useUploadFiles = () => {
const [createActivityUploadedFilesMutation] = useCreateActivityUploadedFilesMutation()

const uploadFiles = async (
files: File[],
activityDetails: { id: string; tripId: string }
Expand All @@ -13,7 +15,7 @@ export const useUploadFiles = () => {

const uploadPromises = files.map(async (file) => {
const { data, error } = await supabase.storage
.from('tabi-memo-uploads')
.from(process.env.NEXT_PUBLIC_BUCKET_NAME!)
.upload(
`trips/${activityDetails.tripId}/activity/${activityDetails.id}/${file.name}`,
file,
Expand All @@ -24,18 +26,33 @@ export const useUploadFiles = () => {
})

const uploadResults = await Promise.all(uploadPromises)

const uploadErrors = uploadResults.filter((result) => result.error)

if (uploadErrors.length) {
if (uploadErrors.length > 0) {
throw new Error(uploadErrors[0].error!.message)
}

// get the public URL of the uploaded files
const results = uploadResults.map((result) => result)
const dataWithPublicUrls = await Promise.all(
results.map((result) => {
const { data: { publicUrl } } = supabase.storage.from(process.env.NEXT_PUBLIC_BUCKET_NAME!).getPublicUrl(result.data!.path!)

return { publicUrl, fileName: result.fileName }
})
)

// create a record in the uploaded_files table
// const uploadedFiles = uploadResults.map((result) => ({
// file_name: result.fileName,
// file_url: result.data?.path
// }))
await createActivityUploadedFilesMutation({
variables: {
objects: dataWithPublicUrls.map((data) => ({
activity_id: activityDetails.id,
file_name: data.fileName,
file_url: data.publicUrl,
}))
},
refetchQueries: ['activityCollection']
})
}

return { uploadFiles }
Expand Down
1 change: 0 additions & 1 deletion app/providers/session-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ export function SessionProvider({
userId: string
}) {
const pathname = usePathname()
console.log(pathname)
const AUTH_PATH_NAMES = ['/signin', '/signup']
return AUTH_PATH_NAMES.includes(pathname) ? (
<SessionContext.Provider value={userId}>{children}</SessionContext.Provider>
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
"react-datepicker": "^5.0.0",
"react-datetime-picker": "^5.6.0",
"react-dom": "^18",
"react-dropzone": "^14.2.3",
"react-slick": "^0.29.0",
"slick-carousel": "^1.8.1"
},
Expand Down
27 changes: 0 additions & 27 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 43cdb4b

Please sign in to comment.