概要
目次
今回は検索結果画面の 検索件数と検索に要した時間を実装します。
以下実装後の様子です。
開発環境
OS:Windows10
IDE:VSCode
"@next/font": "13.1.5",
"autoprefixer": "10.4.14",
"eslint": "8.39.0",
"eslint-config-next": "13.3.1",
"next": "13.3.1",
"postcss": "8.4.23",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-icons": "^4.8.0",
"tailwindcss": "3.3.2"
実装のポイント
APIのレスポンス(earchInformation.formattedTotalResultsとresults.searchInformation.formattedSearchTime)を表示させます。
コード部分
app/search/web/page.jsx
page.jsx
import WebSearchResults from "@/components/WebSearchResults";
import Link from "next/link";
export default async function WebSearchPage({ searchParams }) {
await new Promise((resolve) => setTimeout(resolve,10000));
const response = await fetch(
`https://www.googleapis.com/customsearch/v1?key=${process.env.API_KEY}&cx=${process.env.CONTEXT_KEY}&q=${searchParams.searchTerm}}`
);
if (!response.ok) {
throw new Error("Something went wrong");
}
const data = await response.json();
const results = data.items;
if(!results){
return(
<div className="flex flex-col justify-center items-center pt-10">
<h1 className="text-3xl mb-4">No results found</h1>
<p className="text-lg">
Try searching for something else or go back to the homepage
<Link href="/" className="text-blue-500">
Home
</Link>
</p>
</div>
);
}
+ return <>{results && <WebSearchResults results={data}/>}</>;
}
WebSearchResults
WebSearchResults.jsx
export default function WebSearchResults({results}){
return(
<div>
<p className="text-gray-600 text-sm mb-5 mt-3">
About {results.searchInformation?.formattedTotalResults}
results ({results.searchInformation?.formattedSearchTime} seconds)
</p>
</div>
)
}
参考
その他
Udemy
githubコミット分


