SessionProvider Context Noob Question

If we use getServerSideProps, I can understand where pageProps.session is coming from. However, if we use useSession (getting session on client side), does it somehow attach it to the context still once its fetched? Since it does not come in as a page prop in this case I am a little confused. Thanks!!
8 Replies
Perfect
PerfectOP3y ago
Bump
Ben
Ben3y ago
You don't need to store the session data in ctx, that's where react-query comes in. It will cache the response for you, then when you go to make the request from another component, instead of making a second unnecessary request to the server, it will serve the cached response directly instead. So your request on the client side would look something like
const { data: session } = useSession();
const userData = trpc.useQuery(["userRouter.getUser", session.user!.id], { enabled: !!session.user })
const { data: session } = useSession();
const userData = trpc.useQuery(["userRouter.getUser", session.user!.id], { enabled: !!session.user })
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Perfect
PerfectOP3y ago
Ahh ok, so useSession under the hood is doing this caching for us.
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Ben
Ben3y ago
useQuery is the caching layer. It will cache any asynchronous data for you. You can put an Axios request into useQuery and it'll cache that just like it would with your useSession data. useSession is essentially just going to the SessionProvider and getting that session data for you. Like you can see in my example, we're not using useQuery to store the session data, we're using to store the user object when we make a request to our backend for that user's data(using the getUser endpoint). We are just using the session data to get the user.id, so our API knows which user's data to fetch
Perfect
PerfectOP3y ago
@Kayn so I don’t use any TRPC or useQuery stuff, just useSession. I think you actually answered another question I had, but I was more curious how it’s getting the session data from session provider? Basically just how useSession gets the session All I know is that it does a fetch to the server and then idk what it’s doing behind the scenes with the session provider context or anything
Ben
Ben3y ago
They talk about it in this part of the docs: https://next-auth.js.org/getting-started/client#sessionprovider Not sure if that's what you're looking for
Client API | NextAuth.js
The NextAuth.js client library makes it easy to interact with sessions from React applications.
Want results from more Discord servers?
Add your server