Created
March 14, 2023 09:32
-
-
Save hujuu/245bc288b3d0d30f47039ce663d41a66 to your computer and use it in GitHub Desktop.
swrでテキストインプットのリアルタイム検索
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use client"; | |
import React from "react"; | |
import { useState } from "react"; | |
import useSWR from "swr"; | |
// Add some delay here. | |
const fetcher = (url: string) => | |
Promise.all([ | |
fetch(url), | |
new Promise((res) => setTimeout(res, 600)) | |
]).then(([res]) => res.json()); | |
export default function Search() { | |
const [search, setSearch] = useState("Laptop"); | |
const {data, isLoading} = useSWR( | |
`https://dummyjson.com/products/search?q=${search}`, | |
fetcher, | |
{ | |
keepPreviousData: true | |
} | |
); | |
return ( | |
<div> | |
<h1>SWR Search Example</h1> | |
<div className="search-container"> | |
<input | |
type="text" | |
value={search} | |
onChange={(e) => setSearch(e.target.value)} | |
placeholder="Search Products..." | |
autoFocus | |
/> | |
</div> | |
<div className={isLoading ? "loading" : ""}> | |
{data | |
? data.products.map((item: any) => { | |
return ( | |
<div className="item" key={item.id}> | |
<img src={item.thumbnail} alt={item.title}/> | |
<h3>{item.title}</h3> | |
<p>{item.description}</p> | |
</div> | |
); | |
}) | |
: null} | |
</div> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment