diff --git a/src/components/Dashboard/common/DocumentPrintButton.jsx b/src/components/Dashboard/common/DocumentPrintButton.jsx index b08ded3..a07abe7 100644 --- a/src/components/Dashboard/common/DocumentPrintButton.jsx +++ b/src/components/Dashboard/common/DocumentPrintButton.jsx @@ -1,5 +1,5 @@ import PropTypes from 'prop-types' -import { useState, useEffect, useContext } from 'react' +import { useState, useEffect, useContext, useCallback, useMemo, useRef } from 'react' // import { getModelByName } from '../../../database/ObjectModels' import DocumentPrinterIcon from '../../Icons/DocumentPrinterIcon' import { Button, Dropdown, Modal } from 'antd' @@ -15,6 +15,9 @@ const DocumentPrintButton = ({ ...buttonProps }) => { const { fetchObjects } = useContext(ApiServerContext) + const fetchObjectsRef = useRef(fetchObjects) + fetchObjectsRef.current = fetchObjects + const [documentTemplates, setDocumentTemplates] = useState([]) const [currentDocumentTemplate, setCurrentDocumentTemplate] = useState(null) const [loading, setLoading] = useState(false) @@ -25,34 +28,40 @@ const DocumentPrintButton = ({ // Get the model by name //const model = getModelByName(type) - // Fetch document templates when component mounts or type changes - useEffect(() => { - const loadDocumentTemplates = async () => { - if (!type || token == null) return + const loadDocumentTemplates = useCallback(async () => { + if (!type || token == null) return - setLoading(true) - try { - const result = await fetchObjects('documentTemplate', { - filter: { - objectType: type, - global: false, - active: true - }, - limit: 100 // Get more templates to show in dropdown - }) + setLoading(true) + try { + const result = await fetchObjectsRef.current('documentTemplate', { + filter: { + objectType: type, + global: false, + active: true + }, + limit: 100 // Get more templates to show in dropdown + }) - if (result && result.data) { - setDocumentTemplates(result.data) - } - } catch (error) { - console.error('Error fetching document templates:', error) - } finally { - setLoading(false) + if (result && result.data) { + setDocumentTemplates(result.data) } + } catch (error) { + console.error('Error fetching document templates:', error) + } finally { + setLoading(false) } + }, [type, token]) + // Stable key from objectData._id (excludes _isEditing so toggling edit mode doesn't trigger template reload) + const objectKey = useMemo(() => { + if (!objectData) return null + return objectData._id ?? objectData.id ?? null + }, [objectData]) + + // Fetch document templates when component mounts or objectData, type or token changes + useEffect(() => { loadDocumentTemplates() - }, [type, fetchObjects, token]) + }, [objectKey, token, type, loadDocumentTemplates]) // Handle template selection const handleTemplateSelect = (template) => {