Refactor ObjectForm to improve fetch logic and state management
All checks were successful
farmcontrol/farmcontrol-ui/pipeline/head This commit looks good

- Removed the initialized state and replaced it with a ref to track fetched objects, enhancing clarity in the fetch condition.
- Updated the useEffect hook to streamline the fetch logic, ensuring it only triggers under the correct conditions.
- Reset form fields and activities upon fetching a new object, improving user experience during editing.
This commit is contained in:
Tom Butcher 2026-07-26 01:53:39 +01:00
parent a4346ead98
commit 78dba97107

View File

@ -95,7 +95,6 @@ const ObjectForm = forwardRef(
const [fetchLoading, setFetchLoading] = useState(true)
const [editLoading, setEditLoading] = useState(false)
const [activities, setActivities] = useState([])
const [initialized, setInitialized] = useState(false)
const [isEditing, setIsEditing] = useState(false)
const isEditingRef = useRef(false)
const [formValid, setFormValid] = useState(false)
@ -194,6 +193,7 @@ const ObjectForm = forwardRef(
const currentClearObjectActivityRef = useRef(clearObjectActivity)
const currentHasFilePropertiesRef = useRef(hasFileProperties)
const currentFlushOrphanFilesRef = useRef(flushOrphanFiles)
const fetchedObjectRef = useRef(null)
// Update refs when values change
useEffect(() => {
@ -488,11 +488,22 @@ const ObjectForm = forwardRef(
}, [activities, id, notifyActivityState, handleEditingConflict])
useEffect(() => {
if (connected == true && initialized == false && id && token != null) {
setInitialized(true)
handleFetchObject()
if (connected !== true || !id || token == null) {
return
}
}, [id, initialized, handleFetchObject, token, connected])
const objectKey = `${type}:${id}`
if (fetchedObjectRef.current === objectKey) {
return
}
fetchedObjectRef.current = objectKey
setIsEditing(false)
isEditingRef.current = false
setActivities([])
form.resetFields()
handleFetchObject()
}, [id, type, token, connected, handleFetchObject, form])
useEffect(() => {
if (!id) {