Skip to content

Commit

Permalink
Add handling refetch trips collection
Browse files Browse the repository at this point in the history
  • Loading branch information
kanatagu committed Jan 31, 2024
1 parent 3599251 commit e974fb3
Show file tree
Hide file tree
Showing 7 changed files with 152 additions and 102 deletions.
67 changes: 20 additions & 47 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
'use client'

import {
Heading,
Box,
Expand All @@ -12,58 +13,27 @@ import {
import { useRouter } from 'next/navigation'
import { PrimaryButton } from '@/components/button'
import { Loading } from '@/components/loading'
import { useUserId } from '@/providers/session-provider'

import { TripSearch, TripSort, TripCard } from '@/trip/components'
import { useTripsCollectionQuery, TripsOrderBy } from '@generated/api'
import { useTripsGet } from '@/trip/hooks'

export default function Top({ searchParams }: { searchParams: { q: string } }) {
const router = useRouter()
const bg = useColorModeValue('white', 'gray.800')
const color = useColorModeValue('black', 'gray.300')

const searchWord = searchParams.q
const userId = useUserId()

const { data, loading, fetchMore, refetch } = useTripsCollectionQuery({
variables: {
filter: {
user_id: { eq: userId },
...(searchWord &&
searchWord.length && { title: { like: `%${searchWord}%` } })
},
first: 6,
after: null
}
})

const handleSortBy = (sortObj: TripsOrderBy) => {
refetch({
orderBy: sortObj
})
}
const {
tripsData,
loading,
error,
handleSortBy,
handleLoadMore,
refetchLoading
} = useTripsGet(searchWord)

const handleLoadMore = () => {
fetchMore({
variables: {
after: data?.tripsCollection?.pageInfo.endCursor
},
updateQuery: (previousQueryResult, { fetchMoreResult }) => {
const newEdges = fetchMoreResult?.tripsCollection?.edges
const pageInfo = fetchMoreResult?.tripsCollection?.pageInfo
const previousCollection = previousQueryResult?.tripsCollection
return newEdges && newEdges.length && pageInfo && previousCollection
? {
tripsCollection: {
__typename: previousCollection.__typename,
edges: [...previousCollection.edges, ...newEdges],
pageInfo
},
__typename: previousQueryResult.__typename
}
: previousQueryResult
}
})
}
if (error) throw new Error('Failed to fetch trips')

return (
<Box as="main" minH="100vh" bg={bg} color={color}>
Expand Down Expand Up @@ -101,7 +71,7 @@ export default function Top({ searchParams }: { searchParams: { q: string } }) {
<TripSort sortBy={handleSortBy} />
</GridItem>
</Grid>
{loading || !data?.tripsCollection ? (
{loading || refetchLoading || !tripsData ? (
<Loading />
) : (
<>
Expand All @@ -110,16 +80,19 @@ export default function Top({ searchParams }: { searchParams: { q: string } }) {
mt={{ base: '38px', md: '40px' }}
flexWrap={'wrap'}
>
{data.tripsCollection.edges.length === 0 && (
{tripsData.edges.length === 0 && (
<Text>We couldn&apos;t find any results</Text>
)}
{data.tripsCollection.edges.map((trip) => (
{tripsData.edges.map((trip) => (
<TripCard key={trip.node.id} data={trip} />
))}
</Flex>
{data.tripsCollection.pageInfo.hasNextPage && (
{tripsData.pageInfo.hasNextPage && (
<Box textAlign="center" mt={{ base: '40px', md: '60px' }}>
<PrimaryButton variant="outline" onClick={handleLoadMore}>
<PrimaryButton
variant="outline"
onClick={() => handleLoadMore(tripsData.pageInfo.endCursor)}
>
Load More
</PrimaryButton>
</Box>
Expand Down
103 changes: 49 additions & 54 deletions app/trip/[id]/edit/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import { NetworkStatus } from '@apollo/client'
import { Box, Container, Heading, useColorModeValue } from '@chakra-ui/react'
import { Loading } from '@/components/loading'
import { Header, Footer } from '@/components/navigation'
import { useUserId } from '@/providers/session-provider'
import { TripForm } from '../../components'
import {
Expand Down Expand Up @@ -88,58 +87,54 @@ export default function TripEditPage({ params }: { params: { id: string } }) {
throw new Error('No trip data found')

return (
<>
<Header />
<Box as="main" minH="100svh" bg={bg} color={color}>
<Container
maxW={{ base: '100%', lg: 'container.sm' }}
pt={{ base: '20px', md: '30px' }}
pb={{ base: '40px', md: '80px' }}
>
<Heading as="h1" fontSize={{ base: '2xl', md: '4xl' }}>
Edit Trip
</Heading>
<Box mt="40px">
{!tripDataCollection || tripLoading || !tripsTagsDataArray ? (
<Loading />
) : (
<TripForm
tripDetails={{
id: tripDataCollection.id,
image: tripDataCollection.image_storage_object_id,
title: tripDataCollection.title,
dateFrom: tripDataCollection.date_from,
dateTo: tripDataCollection.date_to,
cost: tripDataCollection.cost,
costUnit: tripDataCollection.cost_unit,
refetch: tripDetailsRefetch,
refetchLoading: tripDetailsRefetchLoading
}}
tripTags={{
data:
tripTagsData?.trip_tagsCollection?.edges.map((tripTag) => ({
id: tripTag.node.id,
tag_id: tripTag.node.tag_id || '',
trip_id: tripTag.node.trip_id || ''
})) || [],
refetch: tripTagsCollectionRefetch,
refetchLoading: tripTagsRefetchLoading
}}
tags={{
data:
tagsData?.tagsCollection?.edges.map((tag) => ({
id: tag.node.id,
name: tag.node.name
})) || [],
refetch: tagsCollectionRefetch,
refetchLoading: tagsRefetchLoading
}}
/>
)}
</Box>
</Container>
</Box>
<Footer />
</>
<Box as="main" minH="100svh" bg={bg} color={color}>
<Container
maxW={{ base: '100%', lg: 'container.sm' }}
pt={{ base: '20px', md: '30px' }}
pb={{ base: '40px', md: '80px' }}
>
<Heading as="h1" fontSize={{ base: '2xl', md: '4xl' }}>
Edit Trip
</Heading>
<Box mt="40px">
{!tripDataCollection || tripLoading || !tripsTagsDataArray ? (
<Loading />
) : (
<TripForm
tripDetails={{
id: tripDataCollection.id,
image: tripDataCollection.image_storage_object_id,
title: tripDataCollection.title,
dateFrom: tripDataCollection.date_from,
dateTo: tripDataCollection.date_to,
cost: tripDataCollection.cost,
costUnit: tripDataCollection.cost_unit,
refetch: tripDetailsRefetch,
refetchLoading: tripDetailsRefetchLoading
}}
tripTags={{
data:
tripTagsData?.trip_tagsCollection?.edges.map((tripTag) => ({
id: tripTag.node.id,
tag_id: tripTag.node.tag_id || '',
trip_id: tripTag.node.trip_id || ''
})) || [],
refetch: tripTagsCollectionRefetch,
refetchLoading: tripTagsRefetchLoading
}}
tags={{
data:
tagsData?.tagsCollection?.edges.map((tag) => ({
id: tag.node.id,
name: tag.node.name
})) || [],
refetch: tagsCollectionRefetch,
refetchLoading: tagsRefetchLoading
}}
/>
)}
</Box>
</Container>
</Box>
)
}
2 changes: 1 addition & 1 deletion app/trip/components/trip-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export const TripForm = ({ tripDetails, tags, tripTags }: TripFormProps) => {
date_to: tripDetails?.dateTo ? getDateObj(tripDetails.dateTo) : null,
image_storage_object_id: tripDetails?.image || null,
selectedTags: tripTags ? tripTags.data.map((tag) => tag.tag_id) : [],
cost: tripDetails?.cost ? tripDetails.cost.toString() : '',
cost: tripDetails?.cost ? tripDetails.cost.toString() : null,
cost_unit: tripDetails?.costUnit
},
resolver: tripSchemaResolver
Expand Down
1 change: 1 addition & 0 deletions app/trip/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { useTripsGet } from './useTripsGet'
export { useTagCreateDelete } from './useTagCreateDelete'
export { useTripCreate } from './useTripCreate'
export { useTripTagCreateDelete } from './useTripTagCreateDelete'
Expand Down
4 changes: 4 additions & 0 deletions app/trip/hooks/useTripCreate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useRouter } from 'next/navigation'
import { formatToISODate } from '@/libs/utils'
import { useUserId } from '@/providers/session-provider'
import { TripSchema } from '../schema'
import { useTripsGet } from '.'
import { useCreateTripMutation, useCreateTripTagMutation } from '@generated/api'

export const useTripCreate = () => {
Expand All @@ -15,6 +16,8 @@ export const useTripCreate = () => {
const [createTripTagMutation, { loading: isTripTagCreating }] =
useCreateTripTagMutation()

const { tripsRefetch } = useTripsGet()

const createTrip = async (data: TripSchema) => {
try {
const res = await createTripMutation({
Expand Down Expand Up @@ -47,6 +50,7 @@ export const useTripCreate = () => {

await Promise.all([...createPromises])

tripsRefetch()
router.push('/')

toast({
Expand Down
4 changes: 4 additions & 0 deletions app/trip/hooks/useTripUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useRouter } from 'next/navigation'
import { formatToISODate } from '@/libs/utils'
import { TripDetailsArgs, TripTagsArgs } from '../components/trip-form'
import { TripSchema } from '../schema'
import { useTripsGet } from '.'
import {
useUpdateTripMutation,
useCreateTripTagMutation,
Expand All @@ -23,6 +24,8 @@ export const useTripUpdate = (
const [deleteTripTagMutation, { loading: isTripTagDeleting }] =
useDeleteTripTagMutation()

const { tripsRefetch } = useTripsGet()

const updateTrip = async (data: TripSchema) => {
if (!tripDetails) throw new Error('Trip details is not found')

Expand Down Expand Up @@ -70,6 +73,7 @@ export const useTripUpdate = (

tripDetails.refetch()
tripTags?.refetch()
tripsRefetch()
router.push(`/trip/${tripDetails.id}`)

toast({
Expand Down
73 changes: 73 additions & 0 deletions app/trip/hooks/useTripsGet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { NetworkStatus } from '@apollo/client'
import { useUserId } from '@/providers/session-provider'
import { useTripsCollectionQuery, TripsOrderBy } from '@generated/api'

export const useTripsGet = (searchWord?: string) => {
const userId = useUserId()

const { data, loading, error, fetchMore, refetch, networkStatus } =
useTripsCollectionQuery({
variables: {
filter: {
user_id: { eq: userId },
...(searchWord &&
searchWord.length && { title: { like: `%${searchWord}%` } })
},
first: 12,
after: null
}
})

const refetchLoading = networkStatus === NetworkStatus.refetch

const tripsRefetch = () => {
refetch({
filter: {
user_id: { eq: userId },
...(searchWord &&
searchWord.length && { title: { like: `%${searchWord}%` } })
},
first: 12,
after: null
})
}

const handleSortBy = (sortObj: TripsOrderBy) => {
refetch({
orderBy: sortObj
})
}

const handleLoadMore = (endCursor: string | null | undefined) => {
fetchMore({
variables: {
after: endCursor
},
updateQuery: (previousQueryResult, { fetchMoreResult }) => {
const newEdges = fetchMoreResult?.tripsCollection?.edges
const pageInfo = fetchMoreResult?.tripsCollection?.pageInfo
const previousCollection = previousQueryResult?.tripsCollection
return newEdges && newEdges.length && pageInfo && previousCollection
? {
tripsCollection: {
__typename: previousCollection.__typename,
edges: [...previousCollection.edges, ...newEdges],
pageInfo
},
__typename: previousQueryResult.__typename
}
: previousQueryResult
}
})
}

return {
tripsData: data?.tripsCollection,
loading,
error,
handleSortBy,
handleLoadMore,
tripsRefetch,
refetchLoading
}
}

0 comments on commit e974fb3

Please sign in to comment.