Skip to content

Commit

Permalink
Fixing the query fetching from the client
Browse files Browse the repository at this point in the history
  • Loading branch information
amankumarrr committed Oct 30, 2024
1 parent f9ae4b6 commit 4780740
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 63 deletions.
39 changes: 28 additions & 11 deletions app/events/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,44 +4,61 @@ import { Blocks } from "@/components/blocks-renderer";
import { componentRenderer } from "@/components/blocks/mdxComponentRenderer";
import { EventsFilter } from "@/components/filter/events";
import { Container } from "@/components/util/container";
import { QueryProvider } from "app/providers/query-provider";
import { getTrimmedEvent } from "@/helpers/getTrimmedEvent";
import { dehydrate, HydrationBoundary, useQuery } from "@tanstack/react-query";
import queryClient from "app/providers/get-query-client";
import { getFutureEvents, getPastEvents } from "hooks/useFetchEvents";
import { useSearchParams } from "next/navigation";
import { TinaMarkdown } from "tinacms/dist/rich-text";

export default function EventsIndexPage({ props, tinaProps }) {
const { filterCategories, futureEventsData, pastEventsData } = props;
const { data } = tinaProps;
// const futureEvents = getTrimmedEvent(futureEventsData);
// const pastEvents = getTrimmedEvent(pastEventsData);
const { data: tinaData } = tinaProps;

const { data: FutureEvents } = useQuery({
queryKey: ["posts"],
queryFn: () => getFutureEvents(),
initialData: futureEventsData,
});
const { data: PastEvents } = useQuery({
queryKey: ["posts"],
queryFn: () => getPastEvents(),
initialData: pastEventsData,
});

const futureEvents = getTrimmedEvent(FutureEvents);
const pastEvents = getTrimmedEvent(PastEvents);

const dehydratedState = dehydrate(queryClient());

const searchParams = useSearchParams();

const defaultToPastTab = searchParams.get("past") === "1";

return (
<QueryProvider>
<HydrationBoundary state={dehydratedState}>
<Container size="small">
<div className="md:flex md:flex-row">
<h1 className="md:mr-12 md:shrink-0 md:basis-64">SSW Events</h1>
<div className="mt-5 min-w-0 max-w-full shrink grow overflow-auto whitespace-normal break-all pb-1 pt-15 md:mr-12 md:shrink-0 md:basis-64">
<TinaMarkdown
content={data.eventsIndex.preface}
content={tinaData.eventsIndex.preface}
components={componentRenderer}
/>
</div>
</div>
<EventsFilter
filterCategories={filterCategories}
sidebarBody={data.eventsIndex.sidebarBody}
sidebarBody={tinaData.eventsIndex.sidebarBody}
defaultToPastTab={defaultToPastTab}
futureEvents={futureEventsData}
pastEvents={pastEventsData}
futureEvents={futureEvents}
pastEvents={pastEvents}
/>
</Container>
<Blocks
prefix="EventsIndexAfterEvents"
blocks={data.eventsIndex.afterEvents}
blocks={tinaData.eventsIndex.afterEvents}
/>
</QueryProvider>
</HydrationBoundary>
);
}
40 changes: 3 additions & 37 deletions app/events/page.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import client from "@/tina/client";

import { getTrimmedEvent } from "@/helpers/getTrimmedEvent";
import { dehydrate, QueryClient } from "@tanstack/react-query";
import { TinaClient } from "app/tina-client";
import {
FUTURE_EVENTS_QUERY_KEY,
getEventsCategories,
getFutureEvents,
getPastEvents,
PAST_EVENTS_QUERY_KEY,
TODAY,
} from "hooks/useFetchEvents";
import { useSEO } from "hooks/useSeo";
Expand All @@ -17,8 +14,6 @@ import EventIndex from "./index";

export const revalidate = 3600;

const DEFAULT_FILTERS = "undefinedundefined";

export async function generateMetadata(): Promise<Metadata> {
const tinaProps = await getData();

Expand All @@ -39,45 +34,17 @@ const getData = async () => {
date: TODAY.toISOString(),
});

const queryClient = new QueryClient();

const seo = tinaProps.data.eventsIndex.seo;

const filterCategories = await getEventsCategories();

// Default filters are set to undefined on initial load to prevent losing the prefetched cache.
// This avoids extra load time on the client side.
const intialCachedQueryForFutureEvent =
FUTURE_EVENTS_QUERY_KEY + DEFAULT_FILTERS;
const intialCachedQueryForPastEvents =
PAST_EVENTS_QUERY_KEY + DEFAULT_FILTERS;

await queryClient.prefetchInfiniteQuery({
/* values of undefined cannot be serialized as JSON, so were passing the values as strings
using concatenation */
queryKey: [intialCachedQueryForFutureEvent],
queryFn: () => getFutureEvents(),
initialPageParam: "",
});

await queryClient.prefetchInfiniteQuery({
/* values of undefined cannot be serialized as JSON, so were passing the values as strings
using concatenation */
queryKey: [intialCachedQueryForPastEvents],
queryFn: () => getPastEvents(),
initialPageParam: "",
});

if (!tinaProps.data.eventsIndex.seo.canonical) {
tinaProps.data.eventsIndex.seo.canonical = `${tinaProps.data.global.header.url}events`;
}

const futureEventsData = getTrimmedEvent(
queryClient.getQueryData([intialCachedQueryForFutureEvent])
);
const pastEventsData = getTrimmedEvent(
queryClient.getQueryData([intialCachedQueryForFutureEvent])
);
const futureEventsData = await getFutureEvents();

const pastEventsData = await getPastEvents();

return {
props: {
Expand All @@ -87,7 +54,6 @@ const getData = async () => {
filterCategories,
futureEventsData,
pastEventsData,
dehydratedState: dehydrate(queryClient),
header: {
url: tinaProps.data.global.header.url,
},
Expand Down
3 changes: 2 additions & 1 deletion app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { MenuWrapper } from "./components/MenuWrapper";
import { WebVitals } from "./components/web-vitals";
import { LiveStream } from "./live-steam-banner/live-stream";
import { DEFAULT } from "./meta-data/default";
import { QueryProvider } from "./providers/query-provider";
import { getMegamenu } from "./utils/get-mega-menu";

dayjs.extend(relativeTime);
Expand Down Expand Up @@ -86,7 +87,7 @@ export default async function RootLayout({
<main className="grow bg-white">
<AppInsightsProvider>
<WebVitals />
{children}
<QueryProvider>{children}</QueryProvider>
</AppInsightsProvider>
</main>
<Footer />
Expand Down
6 changes: 6 additions & 0 deletions app/providers/get-query-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// app/getQueryClient.jsx
import { QueryClient } from "@tanstack/react-query";
import { cache } from "react";

const getQueryClient = cache(() => new QueryClient());
export default getQueryClient;
14 changes: 8 additions & 6 deletions app/providers/query-provider.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { ReactNode, useMemo } from "react";
"use client";

const FIVE_MINS = 1000 * 60 * 5;

Expand All @@ -10,8 +8,12 @@ function makeQueryClient() {
});
}

export const QueryProvider = ({ children }: { children: ReactNode }) => {
const queryClient = useMemo(() => makeQueryClient(), []);
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import React from "react";

export function QueryProvider({ children }) {
const [queryClient] = React.useState(makeQueryClient());

return (
<QueryClientProvider client={queryClient}>
Expand All @@ -24,4 +26,4 @@ export const QueryProvider = ({ children }: { children: ReactNode }) => {
)}
</QueryClientProvider>
);
};
}
14 changes: 6 additions & 8 deletions helpers/getTrimmedEvent.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
export const getTrimmedEvent = (events) =>
events?.pages.flat().flatMap((item) =>
item.eventsCalendarConnection.edges.map((edge) => ({
...edge.node,
startDateTime: new Date(edge.node.startDateTime),
endDateTime: new Date(edge.node.endDateTime),
category: formatCategory(edge.node.category),
}))
) || [];
events.eventsCalendarConnection.edges.map((edge) => ({
...edge.node,
startDateTime: new Date(edge.node.startDateTime),
endDateTime: new Date(edge.node.endDateTime),
category: formatCategory(edge.node.category),
})) || [];

export const formatCategory = (category: string): string => {
{
Expand Down

0 comments on commit 4780740

Please sign in to comment.