50 lines
1.3 KiB
TypeScript
50 lines
1.3 KiB
TypeScript
import { useState, useEffect } from 'react'
|
|
import { useParams } from 'react-router-dom'
|
|
import apiService from '@/services/apiService'
|
|
import { showErrorToast } from '@/utils/toast'
|
|
|
|
export const useMigrantData = (
|
|
populateFormData: (data: any) => void,
|
|
populatePhotoData: (data: any) => void
|
|
) => {
|
|
const { id } = useParams<{ id: string }>()
|
|
const [loading, setLoading] = useState(false)
|
|
const [initialDataLoaded, setInitialDataLoaded] = useState(false)
|
|
|
|
const isEditMode = Boolean(id)
|
|
|
|
useEffect(() => {
|
|
if (isEditMode && id && !initialDataLoaded) {
|
|
loadExistingData()
|
|
}
|
|
}, [id, isEditMode, initialDataLoaded])
|
|
|
|
const loadExistingData = async () => {
|
|
try {
|
|
setLoading(true)
|
|
|
|
const personId = Number.parseInt(id!, 10)
|
|
if (isNaN(personId)) {
|
|
throw new Error("Invalid person ID")
|
|
}
|
|
|
|
const migrantData = await apiService.getMigrantById(personId)
|
|
|
|
populateFormData(migrantData)
|
|
populatePhotoData(migrantData)
|
|
|
|
setInitialDataLoaded(true)
|
|
} catch (error) {
|
|
showErrorToast("Failed to load migrant data for editing.")
|
|
} finally {
|
|
setLoading(false)
|
|
}
|
|
}
|
|
|
|
return {
|
|
loading,
|
|
isEditMode,
|
|
initialDataLoaded,
|
|
setInitialDataLoaded: (loaded: boolean) => setInitialDataLoaded(loaded),
|
|
}
|
|
} |