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

Improve handling of time for server side rendering (WIP) #432

Closed
wants to merge 8 commits into from
1 change: 1 addition & 0 deletions components/HomeSection/Assets.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ const AssetsHomeSection: FC<Props> = ({ date }) => {
address: address || '',
},
skip: assetIds === undefined,
ssr: false,
})
useHandleQueryError(assetsQuery)
const assetData = assetsQuery.data
Expand Down
1 change: 1 addition & 0 deletions components/HomeSection/Auctions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const AuctionsHomeSection: FC<Props> = ({ date }) => {
const { t } = useTranslation('templates')
const auctionAssetsQuery = useFetchAuctionsQuery({
variables: { now: date, address: address || '' },
ssr: false,
})
useHandleQueryError(auctionAssetsQuery)
return (
Expand Down
1 change: 1 addition & 0 deletions components/HomeSection/Featured.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const FeaturedHomeSection: FC<Props> = ({ date }) => {
address: address || '',
},
skip: !FEATURED_TOKEN.length,
ssr: false,
})
useHandleQueryError(featureAssetsQuery)

Expand Down
5 changes: 0 additions & 5 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,6 @@ function AccountProvider({

export type MyAppProps = {
jwt: string | null
now: Date
environment: Environment
}

Expand Down Expand Up @@ -277,15 +276,11 @@ MyApp.getInitialProps = async (
appContext,
)) as AppInitialProps<{}> // force type of props to empty object instead of any so TS will properly require MyAppProps to be returned by this function
const jwt = appContext.ctx.req?.cookies?.[COOKIE_JWT_TOKEN] || null
// Generate the now time, rounded to the second to avoid re-rendering on the client
// TOFIX: find a better way to share the time between the app and document
const now = new Date(Math.floor(Date.now() / 1000) * 1000)
return {
...initialProps,
pageProps: {
...initialProps.pageProps,
jwt,
now,
environment: await getEnvironment(),
},
}
Expand Down
5 changes: 1 addition & 4 deletions pages/_document.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,11 @@ class MyDocument extends Document {
true,
console.error,
)
// Generate the now time, rounded to the second to avoid re-rendering on the client
// TOFIX: find a better way to share the time between the app and document
const now = new Date(Math.floor(Date.now() / 1000) * 1000)
// properly type the AppTree with the props from MyApp
const AppTree = context.AppTree as typeof context.AppTree &
ComponentType<AppInitialProps<MyAppProps>>
// This renders the page and wait for all requests to be resolved
await getDataFromTree(<AppTree pageProps={{ jwt, now, environment }} />) // This `defaultGetInitialProps` should be as late as possible and after the data are resolved by `getDataFromTree`
await getDataFromTree(<AppTree pageProps={{ jwt, environment }} />) // This `defaultGetInitialProps` should be as late as possible and after the data are resolved by `getDataFromTree`
const initialProps = await context.defaultGetInitialProps(context)
return {
...initialProps,
Expand Down
34 changes: 25 additions & 9 deletions pages/checkout/[id].gql
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,26 @@ query Checkout($id: UUID!) {
id
type
asset {
id
chainId
collectionAddress
tokenId
image
name
creator {
address
name
image
verification {
status
}
}
collection {
chainId
address
name
standard
}
}
maker {
address
Expand Down Expand Up @@ -42,11 +59,18 @@ query FetchAssetForCheckout(
chainId
collectionAddress
tokenId
creator {
address
name
image
verification {
status
}
}
collection {
chainId
address
name
standard
}
name
image
Expand All @@ -55,14 +79,6 @@ query FetchAssetForCheckout(
mimetype
}
animationUrl
creator {
address
name
image
verification {
status
}
}
owned: ownership(ownerAddress: $address) {
quantity
}
Expand Down
34 changes: 16 additions & 18 deletions pages/checkout/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
Heading,
Skeleton,
Stack,
useConst,
useToast,
} from '@chakra-ui/react'
import { BigNumber } from '@ethersproject/bignumber'
Expand Down Expand Up @@ -36,11 +37,7 @@ import useRequiredQueryParamSingle from '../../hooks/useRequiredQueryParamSingle
import useSigner from '../../hooks/useSigner'
import SmallLayout from '../../layouts/small'

type Props = {
now: string
}

const CheckoutPage: NextPage<Props> = ({ now }) => {
const CheckoutPage: NextPage = () => {
const signer = useSigner()
const { t } = useTranslation('templates')
const { back, push } = useRouter()
Expand All @@ -49,19 +46,20 @@ const CheckoutPage: NextPage<Props> = ({ now }) => {

const { address } = useAccount()

const date = useMemo(() => new Date(now), [now])
const mountTime = useConst(() => new Date())
const { data: offerData } = useCheckoutQuery({ variables: { id: offerId } })
const offer = offerData?.offer

const { data: assetData } = useFetchAssetForCheckoutQuery({
variables: {
now: date,
now: mountTime,
address: address || '',
chainId: offer?.asset.chainId || 0,
collectionAddress: offer?.asset.collectionAddress || '',
tokenId: offer?.asset.tokenId || '',
},
skip: !offer,
ssr: false,
})
const asset = assetData?.asset

Expand All @@ -70,36 +68,36 @@ const CheckoutPage: NextPage<Props> = ({ now }) => {
[offer],
)
const isSingle = useMemo(
() => asset?.collection.standard === 'ERC721',
[asset],
() => offer?.asset.collection.standard === 'ERC721',
[offer?.asset.collection.standard],
)

const blockExplorer = useBlockExplorer(asset?.chainId)
const blockExplorer = useBlockExplorer(offer?.asset.chainId)

const onPurchased = useCallback(async () => {
if (!asset) return
if (!offer) return
toast({
title: t('offers.checkout.notifications.purchased'),
status: 'success',
})
await push(`/tokens/${asset.id}`)
}, [asset, toast, t, push])
await push(`/tokens/${offer.asset.id}`)
}, [offer, toast, t, push])

if (offer === null || asset === null) {
return <Error statusCode={404} />
}
return (
<SmallLayout>
<Head
title={asset && t('offers.checkout.meta.title', asset)}
title={offer && t('offers.checkout.meta.title', offer.asset)}
description={
asset &&
offer?.asset &&
t('offers.checkout.meta.description', {
name: asset.name,
creator: asset.creator.name || asset.creator.address,
name: offer.asset.name,
creator: offer.asset.creator.name || offer.asset.creator.address,
})
}
image={asset?.image}
image={offer?.asset.image}
/>

<BackButton onClick={back} />
Expand Down
17 changes: 8 additions & 9 deletions pages/collection/[chainId]/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ import {
ModalHeader,
SimpleGrid,
useBreakpointValue,
useConst,
} from '@chakra-ui/react'
import { NextPage } from 'next'
import useTranslation from 'next-translate/useTranslation'
import Error from 'next/error'
import { useRouter } from 'next/router'
import { FC, useCallback, useMemo } from 'react'
import { useCallback, useMemo } from 'react'
import CollectionHeader from '../../../components/Collection/CollectionHeader'
import CollectionHeaderSkeleton from '../../../components/Collection/CollectionHeaderSkeleton'
import CollectionMetrics from '../../../components/Collection/CollectionMetrics'
Expand Down Expand Up @@ -57,11 +59,7 @@ import useRequiredQueryParamSingle from '../../../hooks/useRequiredQueryParamSin
import LargeLayout from '../../../layouts/large'
import { removeEmptyFromObject } from '../../../utils'

type Props = {
now: string
}

const CollectionPage: FC<Props> = ({ now }) => {
const CollectionPage: NextPage = () => {
const { REPORT_EMAIL, PAGINATION_LIMIT } = useEnvironment()
const { query, push, pathname } = useRouter()
const chainId = useRequiredQueryParamSingle<number>('chainId', {
Expand All @@ -73,7 +71,7 @@ const CollectionPage: FC<Props> = ({ now }) => {
{ fallback: 'md' },
)
const { t } = useTranslation('templates')
const date = useMemo(() => new Date(now), [now])
const mountTime = useConst(() => new Date())
const { address } = useAccount()
const { data: collectionData } = useFetchCollectionDetailsQuery({
variables: {
Expand All @@ -98,14 +96,15 @@ const CollectionPage: FC<Props> = ({ now }) => {
const { data: assetData } = useFetchCollectionAssetsQuery({
variables: {
collectionAddress,
now: date,
now: mountTime,
currentAccount: address || '',
limit,
offset,
orderBy,
chainId: chainId,
filter: convertFilterToAssetFilter(filter, date),
filter: convertFilterToAssetFilter(filter, mountTime),
},
ssr: false,
})

const { showFilters, toggleFilters, close, count } =
Expand Down
16 changes: 7 additions & 9 deletions pages/explore/explore.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ import {
ModalHeader,
SimpleGrid,
useBreakpointValue,
useConst,
} from '@chakra-ui/react'
import { NextPage } from 'next'
import useTranslation from 'next-translate/useTranslation'
import { useRouter } from 'next/router'
import { useCallback, useMemo } from 'react'
import { useCallback } from 'react'
import Empty from '../../components/Empty/Empty'
import ExploreTemplate from '../../components/Explore'
import FilterAsset, { NoFilter } from '../../components/Filter/FilterAsset'
Expand Down Expand Up @@ -45,32 +46,29 @@ import usePaginate from '../../hooks/usePaginate'
import usePaginateQuery from '../../hooks/usePaginateQuery'
import { removeEmptyFromObject } from '../../utils'

type Props = {
now: string
}

const ExplorePage: NextPage<Props> = ({ now }) => {
const ExplorePage: NextPage = () => {
const { PAGINATION_LIMIT } = useEnvironment()
const { query, pathname, push } = useRouter()
const isSmall = useBreakpointValue(
{ base: true, md: false },
{ fallback: 'md' },
)
const { t } = useTranslation('templates')
const date = useMemo(() => new Date(now), [now])
const mountTime = useConst(() => new Date())
const { address } = useAccount()
const filter = useAssetFilterFromQuery()
const orderBy = useOrderByQuery<AssetsOrderBy>('CREATED_AT_DESC')
const { page, limit, offset } = usePaginateQuery()
const { data: assetsData } = useFetchAllErc721And1155Query({
variables: {
now: date,
now: mountTime,
address: address || '',
limit,
offset,
orderBy,
filter: convertFilterToAssetFilter(filter, date),
filter: convertFilterToAssetFilter(filter, mountTime),
},
ssr: false,
})

const { showFilters, toggleFilters, close, count } =
Expand Down
16 changes: 6 additions & 10 deletions pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,25 @@
import { Stack } from '@chakra-ui/react'
import { Stack, useConst } from '@chakra-ui/react'
import AssetsHomeSection from 'components/HomeSection/Assets'
import AuctionsHomeSection from 'components/HomeSection/Auctions'
import CollectionsHomeSection from 'components/HomeSection/Collections'
import FeaturedHomeSection from 'components/HomeSection/Featured'
import ResourcesHomeSection from 'components/HomeSection/Resources'
import UsersHomeSection from 'components/HomeSection/Users'
import { NextPage } from 'next'
import { useMemo } from 'react'
import Head from '../components/Head'
import LargeLayout from '../layouts/large'

type Props = {
now: number
}
const HomePage: NextPage<Props> = ({ now }) => {
const date = useMemo(() => new Date(now), [now])
const HomePage: NextPage = () => {
const mountTime = useConst(() => new Date())
return (
<LargeLayout>
<Head />
<Stack spacing={12}>
<FeaturedHomeSection date={date} />
<FeaturedHomeSection date={mountTime} />
<CollectionsHomeSection />
<UsersHomeSection />
<AuctionsHomeSection date={date} />
<AssetsHomeSection date={date} />
<AuctionsHomeSection date={mountTime} />
<AssetsHomeSection date={mountTime} />
<ResourcesHomeSection />
</Stack>
</LargeLayout>
Expand Down
11 changes: 4 additions & 7 deletions pages/tokens/[id]/bid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
Heading,
Icon,
Stack,
useConst,
useToast,
} from '@chakra-ui/react'
import { BigNumber } from '@ethersproject/bignumber'
Expand Down Expand Up @@ -41,11 +42,7 @@ import useRequiredQueryParamSingle from '../../../hooks/useRequiredQueryParamSin
import useSigner from '../../../hooks/useSigner'
import SmallLayout from '../../../layouts/small'

type Props = {
now: string
}

const BidPage: NextPage<Props> = ({ now }) => {
const BidPage: NextPage = () => {
const { OFFER_VALIDITY_IN_SECONDS, AUCTION_VALIDITY_IN_SECONDS } =
useEnvironment()
const signer = useSigner()
Expand All @@ -60,13 +57,13 @@ const BidPage: NextPage<Props> = ({ now }) => {
)
invariant(chainId && collectionAddress && tokenId, 'Invalid asset id')

const date = useMemo(() => new Date(now), [now])
const mountTime = useConst(() => new Date())
const { data } = useBidOnAssetQuery({
variables: {
chainId: parseInt(chainId, 10),
collectionAddress: collectionAddress,
tokenId: tokenId,
now: date,
now: mountTime,
address: address || '',
},
})
Expand Down
Loading