Dan Mercer
Dan Mercer•3y ago

Storing users in Convex

What is the recommended way to create a user in a Convex table corresponding to each user from my IDP? I was doing this
convex.setAuth(idToken);
const createUser = convex.mutation('user/create');
createUser()
.then((convexUser) => {
setConvexUser(convexUser);
});
convex.setAuth(idToken);
const createUser = convex.mutation('user/create');
createUser()
.then((convexUser) => {
setConvexUser(convexUser);
});
but I'm upgrading Convex and now it wants an async getIdToken function instead, and it seems the mutation does not wait for that token process to resolve, so I get an authentication error.
4 Replies
Dan Mercer
Dan MercerOP•3y ago
Heh, I should have checked the docs first I guess 😅 https://docs.convex.dev/using/auth#storing-users-in-convex
Authentication | Convex Developer Hub
Add authentication to your Convex app.
Dan Mercer
Dan MercerOP•3y ago
Switching to useMutation fixed it. Though I'm surprised useMutation waits for the auth to finish but convex.mutation doesn't. Hmm actually that didn't fix it. There's still a race condition between fetching the token and calling the mutation. If I add a forced delay to the getIdToken function, it fails every time.
ballingt
ballingt•3y ago
You can await the setAuth call / do a .then() on the promise that it now returns
const createUser = convex.mutation("user/create");
convex.setAuth(idToken).then(() => {
createUser().then((convexUser) => {
setConvexUser(convexUser);
});
});
const createUser = convex.mutation("user/create");
convex.setAuth(idToken).then(() => {
createUser().then((convexUser) => {
setConvexUser(convexUser);
});
});
but I can understand the expectation that this the mutation would wait for the new auth "if a mutation is invoked after a call to setAuth it will use a token returned from that new auth fetcher" seems fair, I can't think of a case where you wouldn't want this sorry about the trouble here, look for a behavior change here in an upcoming release
Dan Mercer
Dan MercerOP•3y ago
Ah I thought I checked for a return value from setAuth, but I guess I have weekend brain. 😅 That works, thanks so much!

Did you find this page helpful?