Skip to content

Multi-valued argument in the array key for a dependent fetch #674

Answered by sergiodxa
kevinmichaelchen asked this question in Q&A
Discussion options

You must be logged in to vote

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.

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@kevinmichaelchen
Comment options

@sergiodxa
Comment options

Answer selected by kevinmichaelchen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants