swr-site icon indicating copy to clipboard operation
swr-site copied to clipboard

Feedback for “Getting Started – SWR”

Open corysimmons opened this issue 3 years ago • 2 comments

TLDR: const { user, isLoading } = useUser() isn't complete and seems a bit misleading since useUser() should be useUser(userId). Can this be improved?

In the example, you have user needing to be passed down.

function Page () {
  const [user, setUser] = useState(null)

  useEffect(() => {
    fetch('/api/user')
      .then(res => res.json())
      .then(data => setUser(data))
  }, [])

  if (!user) return <Spinner/>

  return <div>
    <Navbar user={user} /> // here
    <Content user={user} /> // here
  </div>
}

...and later on you have const { user, isLoading } = useUser() being used to clean things up...

But you aren't passing in the userId to useUser() ☝️

The solution would have to be pulling the userId out using Context or some other state higher up the component tree. Then you could do something like:

const {userId} = useContext(userContext)
const { user, isLoading } = useUser()

Which is fine, and maybe there is some way to put the userId getter within the useUser hook to make that example work correctly. (this should be done for the docs' sake)

But if the solution involves putting stuff in Context, then why not just put the entire user in Context in the first place?


This isn't meant to naysay SWR. I'm a huge fan, and the hook pattern looks really nice. Just hoping to make the docs and that pattern more complete.

corysimmons avatar May 03 '22 06:05 corysimmons

Came here to ask about this

mortenjust avatar Jun 15 '22 08:06 mortenjust

Came here to ask about this, too

akaz00 avatar Apr 25 '23 10:04 akaz00