-
both Like I previously wasn't needing a hook so i could do this in a loop... |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
You can pass useSWR a an object (docs), which then get passed in to the fetcher. The fetcher can return any promise, including Putting things together
Here's a very simple example to get the idea across. In practice you might want to extract a const People = () => {
const { data } = useSWR(
{ url: "/people", ids: ["1", "2", "3", "4"] },
({ url, ids }) =>
Promise.all(
ids.map((id) =>
fetch(`https://swapi.dev/api${url}/${id}`).then(async (response) => {
// do something in here
const { name } = await response.json()
return { name: name.toUpperCase() }
})
)
)
)
if (!data) return <p>Fail</p>
return (
<ul>
{data.map((r) => (
<li key={r.name}>{r.name}</li>
))}
</ul>
)
} RevalidatingYou can now revalidate the data cached under the matching cache key <button
onClick={() => {
mutate({ url: "/people", ids: ["1", "2", "3", "4"] }, [
{ name: "hehe" },
])
}}
>
Mutate!
</button> That said, it might be preferable to extend the products API so you can filter the products using a search param (e.g. |
Beta Was this translation helpful? Give feedback.
-
I realize that useSWR (
There is this though, in the works(?) that sounds promising ( useSWRList ) #1988 |
Beta Was this translation helpful? Give feedback.
I realize that useSWR (
useSWRImmutable
) is not capable of doing what I want, which is if I make a call and pass it an array of fetch requests (an array because I don't know how many I will need ahead of time)/product/3
,/product/4
,/product/5
] then/product/3
,/product/5
] then/product/3
key
, not each array item.There is this though, in the works(?) that sounds promising ( useSWRList ) #1988