Mutation on queries.
Hey guys, I need to populate empty db entry when a user runs a query, how can we properly do this? currently I have a query and a mutation and I call the mutation everytime along side the query to ensure the db entry exists.
2 Replies
Thanks for posting in <#1088161997662724167>.
Reminder: If you have a Convex Pro account, use the Convex Dashboard to file support tickets.
- Provide context: What are you trying to achieve, what is the end-user interaction, what are you seeing? (full error message, command output, etc.)
- Use search.convex.dev to search Docs, Stack, and Discord all at once.
- Additionally, you can post your questions in the Convex Community's <#1228095053885476985> channel to receive a response from AI.
- Avoid tagging staff unless specifically instructed.
Thank you!
I think that's the only way to go about it. Queries don't modify data. Mutations don't sync data.
So you have to query for the data, and if it doesn't exist then run a mutation to create it. I make sure to wait for the query to resolve and also check in the mutation to avoid creating duplicate data. But then once it's created, the query should automatically update to show the new data.
You could maybe reverse this to have a mutation that's like getOrCreate or getOrUpdate that returns the row ID from the operation. Then you could have a query that skips if no row ID exists.
Here are some other slightly different patterns I've tried out that are basically the same:
- With convex auth (and probably other auth options), you can hook into the createOrUpdateUser function to add/update custom fields to a users table or userSettings table where rows are linked to the auth/user ID. You could also use this to insert rows in other tables with some default values after checking that they don't already exist. I use this to ensure users are assigned the correct access role when they log in or create an account.
- You can have a query that return's the user's data if it exists, or default values if it doesn't. Then have an update function that will createOrUpdate the table row when the user changes the values from these defaults. That way you're not creating additional rows when users only use the default settings. I use this for like UI options