Skip to content

Commit

Permalink
fix: ssr revalidation (#1377)
Browse files Browse the repository at this point in the history
<!--- Please provide a general summary of your changes in the title
above -->

# Pull Request type

<!-- Please try to limit your pull request to one type; submit multiple
pull requests if needed. -->

Please check the type of change your PR introduces:

- [x] Bugfix
- [ ] Feature
- [ ] Code style update (formatting, renaming)
- [ ] Refactoring (no functional changes, no API changes)
- [ ] Build-related changes
- [ ] Documentation content changes
- [ ] Other (please describe):

## What is the current behavior?

<!-- Please describe the current behavior that you are modifying, or
link to a relevant issue. -->

Issue Number: N/A

## What is the new behavior?

<!-- Please describe the behavior or changes that are being added by
this PR. -->

-
-
-

## Does this introduce a breaking change?

- [ ] Yes
- [ ] No

<!-- If this does introduce a breaking change, please describe the
impact and migration path for existing applications below. -->

## Other information

<!-- Any other information that is important to this PR, such as
screenshots of how the component looks before and after the change. -->


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **New Features**
- Introduced a page revalidation function to ensure users see the latest
data immediately after updates.
- Enhanced error handling with redirection to a 404 page for missing
organizations.

- **Bug Fixes**
  - Improved response to data fetching errors.

- **Documentation**
  - Updated schemas for better data validation and type safety.

- **Refactor**
  - Enhanced control flow for page updates in the UI components.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
  • Loading branch information
JoeKarow authored Aug 8, 2024
1 parent 30f4c9f commit 94261b5
Show file tree
Hide file tree
Showing 9 changed files with 78 additions and 13 deletions.
2 changes: 2 additions & 0 deletions apps/app/src/pages/org/[slug]/[orgLocationId]/edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ const OrgLocationPage: NextPage<InferGetServerSidePropsType<typeof getServerSide
const [loading, setLoading] = useState(true)
const notifySave = useNewNotification({ displayText: 'Saved', icon: 'success' })
const { data, status } = api.location.forLocationPageEdits.useQuery({ id: orgLocationId })
const { mutate: revalidatePage } = api.misc.revalidatePage.useMutation()

const { data: alertData } = api.location.getAlerts.useQuery(
{ id: orgLocationId },
Expand Down Expand Up @@ -92,6 +93,7 @@ const OrgLocationPage: NextPage<InferGetServerSidePropsType<typeof getServerSide
onSuccess: () => {
apiUtils.location.invalidate()
apiUtils.service.invalidate()
revalidatePage({ path: router.asPath.replace('/edit', '') })
notifySave()
},
})
Expand Down
31 changes: 21 additions & 10 deletions apps/app/src/pages/org/[slug]/[orgLocationId]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,18 @@ const OrgLocationPage: NextPage = () => {
const theme = useMantineTheme()
const isTablet = useMediaQuery(`(max-width: ${theme.breakpoints.sm})`)

const { data: orgData, status: orgDataStatus } = api.organization.forLocationPage.useQuery(
{ slug },
{ enabled: router.isReady }
)
const { data, status } = api.location.forLocationPage.useQuery(
{ id: orgLocationId },
{ enabled: router.isReady }
)
const {
data: orgData,
status: orgDataStatus,
isError: orgDataIsError,
error: orgDataError,
} = api.organization.forLocationPage.useQuery({ slug }, { enabled: router.isReady })
const {
data,
status,
isError: pageFetchIsError,
error: pageFetchError,
} = api.location.forLocationPage.useQuery({ id: orgLocationId }, { enabled: router.isReady })

const { data: alertData } = api.location.getAlerts.useQuery(
{ id: orgLocationId },
Expand Down Expand Up @@ -84,6 +88,13 @@ const OrgLocationPage: NextPage = () => {
}
}, [])

if (
(orgDataIsError || pageFetchIsError) &&
(orgDataError?.data?.code === 'NOT_FOUND' || pageFetchError?.data?.code === 'NOT_FOUND')
) {
router.replace('/404')
}

if (loading || !data || !orgData || router.isFallback) {
return <OrgLocationPageLoading />
}
Expand Down Expand Up @@ -202,7 +213,7 @@ export const getStaticProps: GetStaticProps<

const orgId = await ssg.organization.getIdFromSlug.fetch({ slug })
if (!orgId?.id) {
return { notFound: true }
return { notFound: true, revalidate: 1 }
}

const [i18n] = await Promise.allSettled([
Expand All @@ -223,7 +234,7 @@ export const getStaticProps: GetStaticProps<
} catch (error) {
const TRPCError = (await import('@trpc/server')).TRPCError
if (error instanceof TRPCError && error.code === 'NOT_FOUND') {
return { notFound: true }
return { notFound: true, revalidate: 1 }
}
return { redirect: { destination: '/500', permanent: false } }
}
Expand Down
2 changes: 2 additions & 0 deletions apps/app/src/pages/org/[slug]/edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,14 @@ const OrganizationPage: NextPageWithOptions<InferGetServerSidePropsType<typeof g
{ slug: pageSlug },
{ enabled: router.isReady }
)
const { mutate: revalidatePage } = api.misc.revalidatePage.useMutation()
const updateBasic = api.organization.updateBasic.useMutation({
onSuccess: (newData) => {
if (data && newData && data.slug !== newData.slug) {
router.replace({ pathname: router.pathname, query: { ...router.query, slug: newData.slug } })
}
apiUtils.organization.forOrgPageEdits.invalidate()
revalidatePage({ path: router.asPath.replace('/edit', '') })
},
})

Expand Down
13 changes: 11 additions & 2 deletions apps/app/src/pages/org/[slug]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,12 @@ const OrganizationPage = ({
}: InferGetStaticPropsType<typeof getStaticProps>) => {
const router = useRouter<'/org/[slug]'>()
const slug = passedSlug ?? router.query.slug
const { data, status } = api.organization.forOrgPage.useQuery({ slug })
const {
data,
status,
isError: pageFetchIsError,
error: pageFetchError,
} = api.organization.forOrgPage.useQuery({ slug })
// const { query } = router
const { t } = useTranslation(formatNS(orgId))
const [activeTab, setActiveTab] = useState<string | null>('services')
Expand Down Expand Up @@ -131,6 +136,10 @@ const OrganizationPage = ({
[isTablet, ref, width]
)

if (pageFetchIsError && pageFetchError.data?.code === 'NOT_FOUND') {
router.replace('/404')
}

if (loading || !data || router.isFallback) {
return <OrgPageLoading />
}
Expand Down Expand Up @@ -289,7 +298,7 @@ export const getStaticProps: GetStaticProps<
} catch (error) {
const TRPCError = (await import('@trpc/server')).TRPCError
if (error instanceof TRPCError && error.code === 'NOT_FOUND') {
return { notFound: true }
return { notFound: true, revalidate: 1 }
} else {
return { redirect: { destination: '/500', permanent: false } }
}
Expand Down
9 changes: 9 additions & 0 deletions packages/api/router/misc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,13 @@ export const miscRouter = defineRouter({
)
return handler(opts)
}),
revalidatePage: permissionedProcedure('createNewOrgQuick')
.input(schema.ZRevalidatePageSchema)
.mutation(async (opts) => {
const handler = await importHandler(
namespaced('revalidatePage'),
() => import('./mutation.revalidatePage.handler')
)
return handler(opts)
}),
})
24 changes: 24 additions & 0 deletions packages/api/router/misc/mutation.revalidatePage.handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { type TRPCHandlerParams } from '~api/types/handler'

import { type TRevalidatePageSchema } from './mutation.revalidatePage.schema'

const revalidatePage = async ({ ctx, input }: TRPCHandlerParams<TRevalidatePageSchema, 'protected'>) => {
try {
if (!ctx.res) {
return {
revalidated: false,
error: 'Response object is not available',
}
}
await ctx.res.revalidate(input.path)
return {
revalidated: true,
}
} catch (error) {
return {
revalidated: false,
error,
}
}
}
export default revalidatePage
4 changes: 4 additions & 0 deletions packages/api/router/misc/mutation.revalidatePage.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { z } from 'zod'

export const ZRevalidatePageSchema = z.object({ path: z.string() })
export type TRevalidatePageSchema = z.infer<typeof ZRevalidatePageSchema>
1 change: 1 addition & 0 deletions packages/api/router/misc/schemas.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// codegen:start {preset: barrel, include: ./*.schema.ts}
export * from './mutation.revalidatePage.schema'
export * from './query.forEditNavbar.schema'
export * from './query.getCountryTranslation.schema'
export * from './query.hasContactInfo.schema'
Expand Down
5 changes: 4 additions & 1 deletion packages/ui/components/sections/Navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ const EditModeBar = () => {
const { t } = useTranslation('common')
const router = useRouter<'/org/[slug]/edit' | '/org/[slug]/[orgLocationId]/edit'>()
const { orgLocationId, slug, orgServiceId } = router.query

const { mutate: revalidatePage } = api.misc.revalidatePage.useMutation()
const apiQuery = (() => {
switch (true) {
case typeof orgServiceId === 'string': {
Expand All @@ -91,6 +91,7 @@ const EditModeBar = () => {
onSuccess: () => {
apiUtils.organization.invalidate()
apiUtils.component.EditModeBar.invalidate()
revalidatePage({ path: router.asPath.replace('/edit', '') })
reverifyNotification()
},
})
Expand All @@ -103,6 +104,7 @@ const EditModeBar = () => {
apiUtils.location.invalidate()
apiUtils.organization.invalidate()
apiUtils.component.EditModeBar.invalidate()
revalidatePage({ path: router.asPath.replace('/edit', '') })
publishedNotification()
},
})
Expand All @@ -114,6 +116,7 @@ const EditModeBar = () => {
onSuccess: () => {
apiUtils.organization.invalidate()
apiUtils.component.EditModeBar.invalidate()
revalidatePage({ path: router.asPath.replace('/edit', '') })
deletedNotification()
},
})
Expand Down

0 comments on commit 94261b5

Please sign in to comment.