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

Bug fixes for tanstack #183

Merged
merged 8 commits into from
Nov 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions apps/frontend/src/app/api/course.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ export type FetchCourseInfosByPageResult = {
nextPage: number | null;
};

const fetchCourseInfosByPage = async (filters: FiltersState, page: number): Promise<FetchCourseInfosByPageResult> => {
const fetchCourseInfosByPage = async (filters: FiltersState): Promise<FetchCourseInfosByPageResult> => {
const url = `${process.env.NEXT_PUBLIC_BACKEND_URL || ""}/courses/search?`;
const params = new URLSearchParams({
page: `${page}`,
page: `${filters.page}`,
schedules: "true",
});

Expand Down Expand Up @@ -64,11 +64,10 @@ const fetchCourseInfosByPage = async (filters: FiltersState, page: number): Prom

export const useFetchCourseInfosByPage = () => {
const filters = useAppSelector((state) => state.filters);
const page = useAppSelector((state) => state.filters.page);

return useQuery({
queryKey: ['courseInfosByPage', filters, page],
queryFn: () => fetchCourseInfosByPage(filters, page),
queryKey: ['courseInfosByPage', filters],
queryFn: () => fetchCourseInfosByPage(filters),
staleTime: STALE_TIME,
placeholderData: keepPreviousData,
});
Expand Down Expand Up @@ -96,7 +95,7 @@ const fetchCourseInfosBatcher = create({

export const useFetchCourseInfo = (courseID: string) => {
return useQuery({
queryKey: ['courseInfo', courseID],
queryKey: ['courseInfo', { courseID }],
queryFn: () => fetchCourseInfosBatcher.fetch(courseID),
staleTime: STALE_TIME,
});
Expand All @@ -105,7 +104,7 @@ export const useFetchCourseInfo = (courseID: string) => {
export const useFetchCourseInfos = (courseIDs: string[]) => {
return useQueries({
queries: courseIDs.map((courseID) => ({
queryKey: ['courseInfo', courseID],
queryKey: ['courseInfo', { courseID }],
queryFn: () => fetchCourseInfosBatcher.fetch(courseID),
staleTime: STALE_TIME,
})),
Expand Down
9 changes: 5 additions & 4 deletions apps/frontend/src/app/api/fce.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from "axios";
import { FCE } from "~/types";
import { GetToken } from "@clerk/types";
import { useQueries, useQuery } from "@tanstack/react-query";
import { useQueries, useQuery, keepPreviousData } from "@tanstack/react-query";
import { STALE_TIME } from "~/app/constants";
import { create, keyResolver, windowScheduler } from "@yornaath/batshit";
import { memoize } from "lodash-es";
Expand Down Expand Up @@ -41,7 +41,7 @@ export const useFetchFCEInfoByCourse = (courseID: string) => {
const { isSignedIn, getToken } = useAuth();

return useQuery({
queryKey: ['fces', courseID, isSignedIn],
queryKey: ['fces', { courseID, isSignedIn }],
queryFn: () => fetchFCEInfosByCourseBatcher(isSignedIn, getToken).fetch(courseID),
staleTime: STALE_TIME,
});
Expand All @@ -50,7 +50,7 @@ export const useFetchFCEInfoByCourse = (courseID: string) => {
export const useFetchFCEInfosByCourse = (courseIDs: string[], isSignedIn: boolean | undefined, getToken: GetToken) => {
return useQueries({
queries: courseIDs.map((courseID) => ({
queryKey: ['fces', courseID, isSignedIn],
queryKey: ['fces', { courseID, isSignedIn }],
queryFn: () => fetchFCEInfosByCourseBatcher(isSignedIn, getToken).fetch(courseID),
staleTime: STALE_TIME,
placeholderData: {courseID, fces: []},
Expand Down Expand Up @@ -85,8 +85,9 @@ const fetchFCEInfosByInstructor = async (instructor: string, isSignedIn: boolean

export const useFetchFCEInfosByInstructor = (instructor: string, isSignedIn: boolean | undefined, getToken: GetToken) => {
return useQuery({
queryKey: ['instructorFCEs', instructor, isSignedIn],
queryKey: ['instructorFCEs', { instructor, isSignedIn }],
queryFn: () => fetchFCEInfosByInstructor(instructor, isSignedIn, getToken),
staleTime: STALE_TIME,
placeholderData: keepPreviousData,
});
};
5 changes: 3 additions & 2 deletions apps/frontend/src/app/api/geneds.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from "axios";
import { Gened } from "~/app/types";
import { GetToken } from "@clerk/types";
import { useQuery } from "@tanstack/react-query";
import { useQuery, keepPreviousData } from "@tanstack/react-query";
import { STALE_TIME } from "~/app/constants";

const fetchGenedsBySchool = async (selectedSchool: string, isSignedIn: boolean | undefined, getToken: GetToken): Promise<Gened[]> => {
Expand Down Expand Up @@ -33,8 +33,9 @@ const fetchGenedsBySchool = async (selectedSchool: string, isSignedIn: boolean |

export const useFetchGenedsBySchool = (selectedSchool: string, isSignedIn: boolean | undefined, getToken: GetToken) => {
return useQuery({
queryKey: ["geneds", selectedSchool],
queryKey: ["geneds", { selectedSchool, isSignedIn }],
queryFn: () => fetchGenedsBySchool(selectedSchool, isSignedIn, getToken),
staleTime: STALE_TIME,
placeholderData: keepPreviousData,
});
};
12 changes: 6 additions & 6 deletions apps/frontend/src/app/fce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ export const aggregateFCEs = (rawFces: FCE[]) => {

for (const fce of fces) {
workload += fce.hrsPerWeek;
teachingRate += fce.rating[7];
courseRate += fce.rating[8];
teachingRate += fce.rating[7] || 0;
courseRate += fce.rating[8] || 0;
semesters.add(sessionToShortString(fce));
}

Expand Down Expand Up @@ -59,7 +59,7 @@ export interface AggregateFCEsOptions {
numSemesters: number;
}

export const filterFCEs = (fces: FCE[], options: AggregateFCEsOptions) => {
export const filterFCEs = (fces: FCE[], options: AggregateFCEsOptions, extraFilters: boolean = false) => {
const sortedFCEs = fces
.filter((fce) => options.counted[fce.semester])
.sort(compareSessions);
Expand All @@ -73,14 +73,14 @@ export const filterFCEs = (fces: FCE[], options: AggregateFCEsOptions) => {
}

// Filter by courses
if (options.filters.type === "courses" && options.filters.courses) {
if (options.filters.type === "courses" && options.filters.courses && extraFilters) {
result = result.filter(({ courseID }) =>
options.filters.courses.includes(courseID),
);
}

// Filter by instructors
if (options.filters.type === "instructors" && options.filters.instructors) {
if (options.filters.type === "instructors" && options.filters.instructors && extraFilters) {
result = result.filter(({ instructor }) =>
options.filters.instructors.includes(instructor),
);
Expand Down Expand Up @@ -137,7 +137,7 @@ export const aggregateCourses = (

for (const courseID of coursesWithoutFCEs) {
const findCourse = courses.filter((course) => course.courseID === courseID);
if (findCourse.length > 0) workload += parseUnits(findCourse[0].units);
if (findCourse.length > 0) workload += parseUnits(findCourse[0]?.units || "0");
}

const totalUnits = courses.reduce((acc, curr) => acc + parseUnits(curr.units) + parseUnits(curr.manualUnits || ""), 0);
Expand Down
14 changes: 0 additions & 14 deletions apps/frontend/src/app/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ export interface UserState {
showFCEs: boolean;
showCourseInfos: boolean;
showSchedules: boolean;
loggedIn: boolean;
showAll: boolean;
fceAggregation: {
numSemesters: number;
Expand All @@ -23,7 +22,6 @@ export interface UserState {
instructors: string[];
}
};
token: string | null;
selectedSchool: string;
selectedTags: string[];
}
Expand All @@ -33,7 +31,6 @@ const initialState: UserState = {
showFCEs: false,
showCourseInfos: true,
showSchedules: false,
loggedIn: false,
showAll: false,
fceAggregation: {
numSemesters: 2,
Expand All @@ -48,7 +45,6 @@ const initialState: UserState = {
instructors: [],
},
},
token: null,
selectedSchool: "SCS",
selectedTags: [],
};
Expand Down Expand Up @@ -78,13 +74,6 @@ export const userSlice = createSlice({
showAll : (state, action: PayloadAction<boolean>) => {
state.showAll = action.payload;
},
logIn: (state) => {
state.loggedIn = true;
},
logOut: (state) => {
state.token = null;
state.loggedIn = false;
},
updateSemestersCounted: (
state,
action: PayloadAction<{ semester: Semester; value: boolean }>
Expand All @@ -98,9 +87,6 @@ export const userSlice = createSlice({
if (isNaN(newNumSemesters)) return;
state.fceAggregation.numSemesters = newNumSemesters;
},
setToken: (state, action: PayloadAction<string>) => {
state.token = action.payload;
},
setFilters: (state, action: PayloadAction<UserState["fceAggregation"]["filters"]>) => {
state.fceAggregation.filters = action.payload;
},
Expand Down
2 changes: 1 addition & 1 deletion apps/frontend/src/app/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ export function getCourseIDs(search: string): string[] {
return search.match(courseIdRegex) || [];
}

export function classNames(...classes) {
export function classNames(...classes: (string | undefined)[]): string {
return classes.filter(Boolean).join(" ");
}

Expand Down
3 changes: 0 additions & 3 deletions apps/frontend/src/components/CourseSearchList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import CourseCard from "./CourseCard";
import Loading from "./Loading";
import { useFetchCourseInfos, useFetchCourseInfosByPage } from "~/app/api/course";
import { Pagination } from "./Pagination";
import { userSlice } from "~/app/user";
import { filtersSlice } from "~/app/filters";

const CoursePage = () => {
Expand Down Expand Up @@ -61,8 +60,6 @@ const CourseSearchList = () => {

const dispatch = useAppDispatch();

dispatch(userSlice.actions.resetFilters()); // Not ideal

const handlePageClick = (page: number) => {
void dispatch(filtersSlice.actions.setPage(page + 1));
};
Expand Down
2 changes: 1 addition & 1 deletion apps/frontend/src/components/FCECard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export const FCECard = ({ fces }: { fces: FCE[] }) => {
return (
<Card>
<Card.Header>FCE Browser</Card.Header>
<FCEDetail fces={fces} />
<FCEDetail fces={fces} extraFilters={true} />
</Card>
);
};
3 changes: 2 additions & 1 deletion apps/frontend/src/components/FCEDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { FCE } from "~/app/types";
import { FCETable } from "./FCETable";
import { useAppSelector } from "~/app/hooks";

export const FCEDetail = ({ fces }: { fces: FCE[] }) => {
export const FCEDetail = ({ fces, extraFilters }: { fces: FCE[], extraFilters?: boolean }) => {
const aggregationOptions = useAppSelector(
(state) => state.user.fceAggregation
);
Expand All @@ -13,6 +13,7 @@ export const FCEDetail = ({ fces }: { fces: FCE[] }) => {
fces={fces}
columnVisibility={{ courseID: false }}
aggregationOptions={aggregationOptions}
extraFilters={extraFilters}
/>
);
};
4 changes: 3 additions & 1 deletion apps/frontend/src/components/FCETable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -144,16 +144,18 @@ export const FCETable = ({
fces,
columnVisibility,
aggregationOptions,
extraFilters,
}: {
fces: FCE[];
columnVisibility: Record<string, boolean>;
aggregationOptions: AggregateFCEsOptions;
extraFilters?: boolean;
}) => {
let aggregateData: AggregatedFCEs | undefined = undefined;
let filteredFCEs = fces;

if (fces) {
filteredFCEs = filterFCEs(fces, aggregationOptions);
filteredFCEs = filterFCEs(fces, aggregationOptions, extraFilters);
aggregateData = aggregateFCEs(filteredFCEs);
}

Expand Down
12 changes: 5 additions & 7 deletions apps/frontend/src/components/GenedsViewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,13 @@ const GenedsViewer = () => {
const selectedTags = useAppSelector((state) => state.user.selectedTags);
const aggregationOptions = useAppSelector((state) => state.user.fceAggregation);
const { isSignedIn, getToken } = useAuth();
const { isPending, error, data: geneds } = useFetchGenedsBySchool(selectedSchool, isSignedIn, getToken);

const [tagQuery, setTagQuery] = useState("");
const [tags, setTags] = useState<string[]>([]);
const [data, setData] = useState<Gened[]>([]);
const [data, setData] = useState<Gened[]>(geneds || []);
const [searchQuery, setSearchQuery] = useState("");

const { isPending, error, data: geneds } = useFetchGenedsBySchool(selectedSchool, isSignedIn, getToken);

const deleteTag = (tagToDelete: string) => {
dispatch(userSlice.actions.setSelectedTags(selectedTags.filter((tag) => tag !== tagToDelete)));
};
Expand Down Expand Up @@ -73,11 +72,10 @@ const GenedsViewer = () => {
}

useEffect(() => {
if (geneds && geneds?.map) {
if (geneds && geneds.length > 0) {
let mappedGeneds = geneds.map(gened => {
const instructor = gened.fces[0]?.instructor;

const filtered = filterFCEs(gened.fces, aggregationOptions);
const instructor = filtered[0]?.instructor;
const aggregated = aggregateFCEs(filtered);
return {
...gened,
Expand All @@ -102,7 +100,7 @@ const GenedsViewer = () => {
setData(mappedGeneds);
setTags([...new Set(geneds.map(gened => gened.tags).flat().filter((tag) => tag !== undefined))]);
}
}, [geneds, geneds?.map, selectedTags, searchQuery]);
}, [geneds, selectedTags, searchQuery, aggregationOptions]);

return (
<div className="p-3 m-2 bg-white rounded">
Expand Down
4 changes: 3 additions & 1 deletion apps/frontend/src/components/InstructorDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ import { useAuth } from "@clerk/nextjs";
type Props = {
name: string;
showLoading: boolean;
extraFilters?: boolean;
};

const InstructorDetail = ({ name, showLoading }: Props) => {
const InstructorDetail = ({ name, showLoading, extraFilters }: Props) => {
const aggregationOptions = useAppSelector(
(state) => state.user.fceAggregation
);
Expand Down Expand Up @@ -47,6 +48,7 @@ const InstructorDetail = ({ name, showLoading }: Props) => {
<InstructorFCEDetail
fces={fces}
aggregationOptions={aggregationOptions}
extraFilters={extraFilters}
/>
</div>
</Card>
Expand Down
3 changes: 3 additions & 0 deletions apps/frontend/src/components/InstructorFCEDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,18 @@ import { AggregateFCEsOptions } from "~/app/fce";
export const InstructorFCEDetail = ({
fces,
aggregationOptions,
extraFilters,
}: {
fces: FCE[];
aggregationOptions: AggregateFCEsOptions;
extraFilters?: boolean;
}) => {
return (
<FCETable
fces={fces}
columnVisibility={{ instructor: false }}
aggregationOptions={aggregationOptions}
extraFilters={extraFilters}
/>
);
};
4 changes: 0 additions & 4 deletions apps/frontend/src/components/InstructorSearchList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import React, { useEffect, useState } from "react";
import InstructorDetail from "./InstructorDetail";
import { useFetchAllInstructors } from "~/app/api/instructors";
import { instructorsSlice } from "~/app/instructors";
import { userSlice } from "~/app/user";

const RESULTS_PER_PAGE = 10;

Expand All @@ -25,7 +24,6 @@ const InstructorSearchList = () => {
} else {
const searchResults = fuse.search(search).map(({item}) => item);
setResults(searchResults);
console.log(searchResults)
dispatch(instructorsSlice.actions.setNumResults(searchResults.length));
}
}, [fuse, search]);
Expand All @@ -34,8 +32,6 @@ const InstructorSearchList = () => {
const curPage = useAppSelector((state) => state.instructors.instructorPage);
const loading = useAppSelector((state) => state.instructors.instructorsLoading);

dispatch(userSlice.actions.resetFilters()); // Not ideal

const handlePageClick = (page: number) => {
dispatch(instructorsSlice.actions.setInstructorPage(page + 1));
};
Expand Down
Loading
Loading