Skip to content

Instantly share code, notes, and snippets.

@ChristopherChudzicki
Last active September 13, 2024 18:30
Show Gist options
  • Save ChristopherChudzicki/ab11931ace608d6ab4e36392c40a38e8 to your computer and use it in GitHub Desktop.
Save ChristopherChudzicki/ab11931ace608d6ab4e36392c40a38e8 to your computer and use it in GitHub Desktop.
prefetching queries with nextjs
diff --git a/frontends/main/src/app-pages/DepartmentListingPage/DepartmentListingPage.tsx b/frontends/main/src/app-pages/DepartmentListingPage/DepartmentListingPage.tsx
index 26e84e977..e19413689 100644
--- a/frontends/main/src/app-pages/DepartmentListingPage/DepartmentListingPage.tsx
+++ b/frontends/main/src/app-pages/DepartmentListingPage/DepartmentListingPage.tsx
@@ -21,6 +21,7 @@ import type {
import {
useLearningResourcesSearch,
useSchoolsList,
+ learningResourcesKeyFactory,
} from "api/hooks/learningResources"
import {
RiPaletteLine,
@@ -34,6 +35,8 @@ import {
} from "@remixicon/react"
import { HOME } from "@/common/urls"
+import { useQueries } from "api/ssr"
+
const SCHOOL_ICONS: Record<string, React.ReactNode> = {
// School of Architecture and Planning
"https://sap.mit.edu/": <RiBuilding2Line />,
@@ -196,16 +199,27 @@ const aggregateByDepartment = (
)
}
-const DepartmentListingPage: React.FC = () => {
- const schoolsQuery = useSchoolsList()
- const courseQuery = useLearningResourcesSearch({
+/**
+ * Store queries separately so we can prefetch them in a server component
+ *
+ * This is a simple case. Trickier when the queries are based on url parameters
+ * or have other queries as dependencies.
+ */
+const queries = [
+ learningResourcesKeyFactory.schools(),
+ learningResourcesKeyFactory.search({
resource_type: ["course"],
aggregations: ["department"],
- })
- const programQuery = useLearningResourcesSearch({
+ }),
+ learningResourcesKeyFactory.search({
resource_type: ["program"],
aggregations: ["department"],
- })
+ }),
+] as const
+
+const DepartmentListingPage: React.FC = () => {
+ const [schoolsQuery, courseQuery, programQuery] = useQueries({ queries })
+
const courseCounts = courseQuery.data
? aggregateByDepartment(courseQuery.data)
: {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment