Multi-valued argument in the array key for a dependent fetch #674
-
I have an app that has two entities: I'm making a call to fetch a paginated list of const { data: widgets } = useSWR("/api/widgets", fetchWidgets, {suspense: true}) But then, to fetch the users, I'm doing something which seems sub-optimal (since I'm losing out on de-duping and caching benefits): const fetchUsers = async (keyName, userIDs) => {
// logic to fetch users
}
const userIDs = widgets.map(w => w.userID)
const { data: users } = useSWR(
// the key
["/api/users", userIDs],
// the fetcher
fetchUsers,
// SWR options
{suspense: true},
) We can run into duplicates if there are multiple Regarding caching, the above isn't great either. We're caching What I'd like is to have a hook per |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
So the solution I'm going with for now is:
|
Beta Was this translation helpful? Give feedback.
-
I suppose you have a Widget component? You could do something like this: function WidgetList() {
const { data: widgetList } = useWidgetList() // this fetch the list of widgets using SWR
return widgetList.map(widget => <Widget key={widget.id} {...widget} />)
}
function Widget({ userId, ...props }) {
const { data: user } = useUser(userId) // this fetch the user using SWR
return <WidgetUI user={user} widget={props} />
} This way, each widget fetches the user assigned to it, if two widgets share the same author because the user ID will be the same then SWR will dedupe the request and only fetch that user one time. |
Beta Was this translation helpful? Give feedback.
I suppose you have a Widget component? You could do something like this:
This way, each widget fetches the user assigned to it, if two widgets share the same author because the user ID will be the same then SWR will dedupe the request and only fetch that user one time.