j. henry
j. henry•5d ago

Batch operations and cache invalidation

Sometimes the thing that makes Convex amazing is also challenging. 😂 I have a React Native component that is built using a convex query to retrieve a set of data (for example, information on multiple people). The query returns a list of objects. In the UI, one person is displayed at a time and the user can decide what to do with them - delete, keep, etc. Very "tinder-vibes". Executing the CRUD operations immediately upon action means the original query is invalidated (because an object was deleted, let's say) and the list of objects/people is also updated. This ultimately causes a weird user experience. I also tried managing state in a different way and batch updated the people. This process can be slow though. Any thoughts or ideas?
2 Replies
Convex Bot
Convex Bot•5d ago
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!
hasanaktasTR
hasanaktasTR•5d ago
My solution in these cases is to use useConvex().query(...) to send a single request. Whenever you want to refresh the list, you maintain your own state in React. For example, you pull 10 users for each request and then delete them from the list.
const convex=useConvex()
const [users,setUsers]=React.useState([])
const reactionMutation=useMutation(...)

const getUsers=async()=>{
const data= await convex.query(...)
return data
}

React.useEffect(()=>{
if(users.length>0){
return
}
getUsers().then(users=>setUsers(users))
},[users])



const reaction=async(id:string)=>{
await reactionMutation(id)
setUsers(prevUsers=>prevUsers.filter(prevUser=>prevUser._id !== id))
}
const convex=useConvex()
const [users,setUsers]=React.useState([])
const reactionMutation=useMutation(...)

const getUsers=async()=>{
const data= await convex.query(...)
return data
}

React.useEffect(()=>{
if(users.length>0){
return
}
getUsers().then(users=>setUsers(users))
},[users])



const reaction=async(id:string)=>{
await reactionMutation(id)
setUsers(prevUsers=>prevUsers.filter(prevUser=>prevUser._id !== id))
}
This way, the query won't be recalculated each time the reaction is called. When your list is empty, you can call query again and update your list.

Did you find this page helpful?