Project 17: Search Results Page
React Engineer
Builds on these lessons
Step 1 of 2
Project
useQuery Basics
Replace a manual useEffect/fetch pair with const { data, isLoading } = useQuery({ queryKey: ["results", query], queryFn: () => fetchResults(query) }). TanStack Query handles the loading state, caching, and re-fetching for you — a large amount of the boilerplate a hand-written fetch effect needs.
🎯 Your Task
Please add the exact code shown in the light gray box below to your editor.Do not delete your previous code, just insert these new lines in the correct place!
import { useQuery } from "@tanstack/react-query";
function fetchResults(query) {
return fetch("/api/search?q=" + query).then((res) => res.json());
}
export default function SearchResultsPage() {
const query = "react";
const { data, isLoading } = useQuery({
queryKey: ["results", query],
queryFn: () => fetchResults(query)
});
if (isLoading) return <p>Loading...</p>;
return <p>{data.length} results</p>;
}