Data Mutation with React Query
Using React Query enhances both readability and provides a faster development process. When implementing data mutations with React Query in conjunction with server actions, follow this naming convention for consistency:
// Naming convention for React Query hooks
data: response_[functionName];
mutate: server_[functionName];
isPending: loading_[functionName];
error: error_[functionName];
After completing any mutation operation, it's important to refresh the router to fetch the latest data:
router.refresh();
This approach provides several benefits:
- Consistent naming patterns across the application
- Improved code readability
- Automatic handling of loading and error states
- Efficient data fetching and caching
const {
data: response_updateEntity,
mutate: server_updateEntity,
isPending: loading_updateEntity,
error: error_updateEntity,
} = useMutation({
mutationFn: updateEntity,
onSuccess: () => {
router.refresh();
toast.success(
response_updateEntity?.message || 'Entity updated successfully'
);
setIsSubmitting(false);
router.push('/entities/details/' + entityData.id);
},
onError: (error: any) => {
console.error('Error updating entity:', error);
toast.error(error?.message || 'Error updating entity');
},
});