Fix form keyboard issues and sticky footers in agent screens
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import type { AgentLoanCategory } from '../types/agentTypes';
|
||||
import { validateLoanRequest } from '../utils/agentValidation';
|
||||
import { useSubmitAgentLoanRequestMutation } from '../services/agentApi';
|
||||
import { useAppDispatch } from '../../../app/hooks';
|
||||
import { agentActions } from '../store/agentSlice';
|
||||
|
||||
export interface LoanFormData {
|
||||
customerId: string;
|
||||
customerName: string;
|
||||
customerPhone: string;
|
||||
category: AgentLoanCategory | null;
|
||||
amount: string;
|
||||
tenureMonths: string;
|
||||
purpose: string;
|
||||
monthlyIncome: string;
|
||||
}
|
||||
|
||||
const initialData: LoanFormData = {
|
||||
customerId: '',
|
||||
customerName: '',
|
||||
customerPhone: '',
|
||||
category: null,
|
||||
amount: '',
|
||||
tenureMonths: '12',
|
||||
purpose: '',
|
||||
monthlyIncome: '',
|
||||
};
|
||||
|
||||
export const useLoanRequestForm = (initialCategory?: AgentLoanCategory, customerId?: string) => {
|
||||
const [data, setData] = useState<LoanFormData>({
|
||||
...initialData,
|
||||
category: initialCategory || null,
|
||||
customerId: customerId || '',
|
||||
});
|
||||
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [submitRequest, { isLoading }] = useSubmitAgentLoanRequestMutation();
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const updateField = useCallback((field: keyof LoanFormData, value: string) => {
|
||||
setData((prev) => ({ ...prev, [field]: value }));
|
||||
if (errors[field]) {
|
||||
setErrors((prev) => {
|
||||
const newErrors = { ...prev };
|
||||
delete newErrors[field];
|
||||
return newErrors;
|
||||
});
|
||||
}
|
||||
}, [errors]);
|
||||
|
||||
const validate = useCallback(() => {
|
||||
const result = validateLoanRequest(data);
|
||||
setErrors(result.errors);
|
||||
return result.isValid;
|
||||
}, [data]);
|
||||
|
||||
const submit = useCallback(async () => {
|
||||
if (!validate()) return null;
|
||||
|
||||
try {
|
||||
const result = await submitRequest({
|
||||
...data,
|
||||
amount: Number(data.amount),
|
||||
tenureMonths: Number(data.tenureMonths),
|
||||
monthlyIncome: Number(data.monthlyIncome),
|
||||
category: data.category!,
|
||||
}).unwrap();
|
||||
|
||||
dispatch(agentActions.addLoanRequest(result));
|
||||
return result;
|
||||
} catch (err) {
|
||||
console.error('Failed to submit loan request', err);
|
||||
return null;
|
||||
}
|
||||
}, [data, validate, submitRequest, dispatch]);
|
||||
|
||||
return {
|
||||
data,
|
||||
errors,
|
||||
updateField,
|
||||
submit,
|
||||
isSubmitting: isLoading,
|
||||
validate,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user