Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conditional fetching #50

Closed
bywo opened this issue Oct 30, 2019 · 4 comments
Closed

Conditional fetching #50

bywo opened this issue Oct 30, 2019 · 4 comments
Labels

Comments

@bywo
Copy link

bywo commented Oct 30, 2019

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!

@shuding
Copy link
Member

shuding commented Oct 30, 2019

@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} />

@bywo
Copy link
Author

bywo commented Oct 30, 2019

Sweet. Thanks for the quick reply!

@dededavida
Copy link

I did it the same way but my data remains undefined forever

@dededavida
Copy link

someone had this problem, can give a light

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants