Swr: Conditional fetching

Created on 31 Oct 2019  路  4Comments  路  Source: vercel/swr

Hey, thanks for putting together this library.

I'm curious how you think about conditional fetching since we can't use conditionals with React hooks. For example, say we have a storefront with a list of items. And if the current user has special access, each item will get augmented with a discount.

In totally invalid React pseudocode:

const {data: user} = userSWR(`/api/me`)
const {data: items} = useSWR(`/api/items`)

let discounts = []
if (user.isSpecial) {
  const {data} = useSWR(`/api/discounts`)
  if (data) { discounts = data }
}

return <ItemList items={items} discounts={discounts} />

Being able to pass fetch in gives us an escape hatch, but I'm not sure if that's how you intended it to be used.

const {data: user} = userSWR(`/api/me`)
const {data: items} = useSWR(`/api/items`)
const {data: discounts} = useSWR(`/api/discounts`, (query) => {
  if (user.isSpecial) {
    return fetch(query)
  } else {
    return []
  }
});

return <ItemList items={items} discounts={discounts} />

How would you go about implementing this pattern? Thanks!

question

Most helpful comment

@bywo yep there is a way to do that very easily: just use null as the key so it won't fetch.

For example:

const {data: user} = userSWR(`/api/me`)
const {data: items} = useSWR(`/api/items`)

let discounts = []
const {data} = useSWR(user.isSpecial ? `/api/discounts` : null)
if (data) { discounts = data }

return <ItemList items={items} discounts={discounts} />

All 4 comments

@bywo yep there is a way to do that very easily: just use null as the key so it won't fetch.

For example:

const {data: user} = userSWR(`/api/me`)
const {data: items} = useSWR(`/api/items`)

let discounts = []
const {data} = useSWR(user.isSpecial ? `/api/discounts` : null)
if (data) { discounts = data }

return <ItemList items={items} discounts={discounts} />

Sweet. Thanks for the quick reply!

I did it the same way but my data remainsundefined forever

someone had this problem, can give a light

Was this page helpful?
0 / 5 - 0 ratings