refactor: Simplify URL parameter handling by removing the isInitialized flag and directly using derived URL parameters for state and data fetching.

This commit is contained in:
pradeepkumar
2026-02-01 21:58:57 +05:30
parent f48c665b0a
commit ad2d2dfbf4

View File

@@ -237,6 +237,11 @@ function ProfileCard({ profile }: ProfileCardProps) {
function ProfilesPageContent() {
const searchParams = useSearchParams();
// Get URL params directly for use in effects
const typeFromUrl = searchParams.get('type');
const nameFromUrl = searchParams.get('name') || '';
const locationFromUrl = searchParams.get('location') || '';
// State for API data
const [agents, setAgents] = useState<PublicAgentProfile[]>([]);
const [agentTypes, setAgentTypes] = useState<AgentType[]>([]);
@@ -248,28 +253,17 @@ function ProfilesPageContent() {
const [totalResults, setTotalResults] = useState(0);
// State for search and filters - initialize from URL params
const [searchQuery, setSearchQuery] = useState(() => searchParams.get('name') || '');
const [activeTypeId, setActiveTypeId] = useState<string | null>(() => searchParams.get('type'));
const [isInitialized, setIsInitialized] = useState(false);
const [searchQuery, setSearchQuery] = useState(nameFromUrl);
const [activeTypeId, setActiveTypeId] = useState<string | null>(typeFromUrl);
const [listingType, setListingType] = useState<'agents' | 'lenders'>('agents');
const [isFilterModalOpen, setIsFilterModalOpen] = useState(false);
const [filters, setFilters] = useState<FilterState>({});
// Mark as initialized after first render and sync with URL param changes
// Sync state when URL params change (e.g., browser back/forward, client-side navigation)
useEffect(() => {
setIsInitialized(true);
}, []);
// Sync state when URL params change (e.g., browser back/forward)
useEffect(() => {
if (isInitialized) {
const type = searchParams.get('type');
const name = searchParams.get('name');
setActiveTypeId(type);
setSearchQuery(name || '');
}
}, [searchParams, isInitialized]);
setActiveTypeId(typeFromUrl);
setSearchQuery(nameFromUrl);
}, [typeFromUrl, nameFromUrl]);
// Fetch agent types and filter fields on mount
useEffect(() => {
@@ -320,10 +314,9 @@ function ProfilesPageContent() {
}
// Add location from URL params
const location = searchParams.get('location');
if (location) {
if (locationFromUrl) {
// Try to set as city first
params.city = location;
params.city = locationFromUrl;
}
// Add dynamic profile field filters
@@ -348,14 +341,12 @@ function ProfilesPageContent() {
} finally {
setLoading(false);
}
}, [currentPage, searchQuery, activeTypeId, searchParams, filters]);
}, [currentPage, searchQuery, activeTypeId, locationFromUrl, filters]);
// Fetch agents when filters change (only after initialization)
// Fetch agents when filters change
useEffect(() => {
if (isInitialized) {
fetchAgents();
}
}, [fetchAgents, isInitialized]);
fetchAgents();
}, [fetchAgents]);
const toggleFilter = (fieldSlug: string, optionValue: string) => {
setFilters(prev => {