Hello everyone, I have a weird issue
Hello everyone, I have a weird issue with convex auth and tanstack start, basically I have a function which should return some data based on userId, e.g.
const userId = await getAuthUserId(ctx)
if (!userId) throw new Error('Not signed in')
However on the first or initial render the userId is null and I get an error, however if i for example just console.log this on the second run which is right after I get the correct userId.
The query in which I call this function is wrapped in the <Authenticated> component which from my understanding should wait until the Auth layer is done loading so I really dont understand why would this userId be null on first run
4 Replies
Just to understand better
The error in question here is ‘Not signed in’ right?
Yes, but also no, since I am authenticated in the client as should be the case by:
const RouteComponent = () => {
return (
<Authenticated>
<Outlet />
</Authenticated>
);
};
Even on backend I am signed in, but not on the initial render
Could this be related to ssr?
Can you try doing the if statement to include userId != null on client?
When query is still not connected your variable will be null that hosts the information from host. I don’t use tanstack start personally but i can spin up an example if that doesn’t solve it.
I mean it wont solve but let me show you real example.
const { data: examples } = useSuspenseQuery( convexQuery(api.example.functions.getExamplesByUser, {}),
);
export const getExamplesByUser = queryWithRLS({
args: {
},
handler: async (ctx,) => {
const userId = await getAuthUserId(ctx)
if (!userId) {
//I can either throw error or return []
}
return await ctx.db
.query('examples')
=>
q.eq('created_by', userId).eq('is_deleted', false),
)
.collect()
},
})
Throwing an error actually crashes my site (console error is something like switching to client render to error) and returning an [] syncs client to incorrect server state as there is data
While the [] example is not good it is better than the breaking whole site however both should be solvable
I managed to resolve this, thank you @Hmza