Skip to content

Commit

Permalink
Use react-query to improve query performance
Browse files Browse the repository at this point in the history
  • Loading branch information
Willdotwhite committed Aug 8, 2024
1 parent 8c25557 commit 58f241c
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 26 deletions.
30 changes: 29 additions & 1 deletion ui/src/api/post.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,35 @@
import {useMutation, UseMutationOptions, UseMutationResult, useQueryClient} from "react-query";
import {
useMutation,
UseMutationOptions,
UseMutationResult,
useQuery,
useQueryClient,
UseQueryResult
} from 'react-query';
import {useApiRequest} from "./apiRequest.ts";
import {Post, PostApiResult, postFromApiResult} from "../common/models/post.ts";
import {useAuth} from './AuthContext.tsx';
import {useSearchParams} from 'react-router-dom';

export function usePosts(): UseQueryResult<Post[], Error> {
const [searchParams, _] = useSearchParams();
const { token } = useAuth() ?? {};
const apiRequest = useApiRequest();

const isOnlyBookmarked = searchParams.get('bookmarked') === "true"
const path = isOnlyBookmarked ? "posts/favourites" : "posts"
const url = `/${path}?${searchParams}`

return useQuery(
["posts", "list", searchParams.toString() ?? ""],
() => {
return apiRequest<PostApiResult[]>(url, {method: "GET", authToken: token});
},
{
select: (posts: PostApiResult[]) => posts.map(postFromApiResult),
}
);
}

const REPORT_POST_QUERY_KEY = ["posts", "report"] as const;

Expand Down
30 changes: 6 additions & 24 deletions ui/src/pages/home/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,46 +5,28 @@ import {useEffect, useState} from "react";
import {PostTile} from "../../common/components/PostTile.tsx";
import {Onboarding} from "./components/Onboarding.tsx";
import {SiteIntro} from "./components/SiteIntro.tsx";
import {useAuth} from "../../api/AuthContext.tsx";
import {Post} from "../../common/models/post.ts";
import {Post} from '../../common/models/post.ts';
import {usePosts} from '../../api/post.ts';

export const Home: React.FC = () => {
const [searchParams, setSearchParams] = useSearchParams();
const [posts, setPosts] = useState<Post[]>([]);
const [isViewingBookmarks, setIsViewingBookmarks] = useState<boolean>(searchParams.get('bookmarked') === "true");
const { token } = useAuth() ?? {};

// Trigger API call every time query string changes
// Not sure if we actually need react-query here, but I'm keeping it everywhere else for now to avoid unnecessary work
const posts = usePosts();

useEffect(() => {
const isOnlyBookmarked = searchParams.get('bookmarked') === "true"
const path = isOnlyBookmarked ? "posts/favourites" : "posts"
setIsViewingBookmarks(isOnlyBookmarked)
searchParams.delete('bookmarked')

const url = new URL(path + "?" + searchParams.toString(), import.meta.env.VITE_API_URL)
const init: RequestInit = {method: "GET", headers: {"Content-Type": "application/json"}}

if (token) {
// @ts-ignore
init.headers['Authorization'] = `Bearer ${token}`
}

fetch(url, init)
.then(res => res.json())
.then(setPosts)
}, [searchParams])

// console.log(posts)

return (
<main>
<Onboarding />
<SiteIntro />
<SearchFormWrapper searchParams={searchParams} setSearchParams={setSearchParams} />

{posts?.length > 0
? <PostsToDisplay posts={posts} />
{posts?.data?.length
? <PostsToDisplay posts={posts.data!} />
: <NoPostsToDisplay isViewingBookmarks={isViewingBookmarks} />
}
</main>
Expand Down
10 changes: 9 additions & 1 deletion ui/src/pages/home/components/SearchForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ import {useState} from "react";
import {SortingOptions} from "./SortingOptions.tsx";
import {iiicon} from "../../../common/utils/iiicon.tsx";
import {blankSearchParameters} from "../models/SearchParameters.ts";
import {useSearchParams} from 'react-router-dom';

export const SearchForm: React.FC<{
params: FormikSearchFormParameters
}> = ({params}) => {
const [searchParams, _] = useSearchParams();
const {values, handleChange, handleBlur} = params;
const [showAdvancedSearchOptions, setShowAdvancedSearchOptions] = useState(false);

Expand Down Expand Up @@ -62,7 +64,13 @@ export const SearchForm: React.FC<{
<div className="text-center">
<button
id="clear-search-button"
onClick={() => {params.resetForm({values: blankSearchParameters})}}
onClick={() => {
const isOnlyBookmarked = searchParams.get('bookmarked') === "true"
params.resetForm({values: blankSearchParameters})
if (isOnlyBookmarked) {
searchParams.set('bookmarked', 'true');
}
}}
type="button"
>
Clear Search
Expand Down

0 comments on commit 58f241c

Please sign in to comment.