feat(FE): Persist search in UI store and reset on exit

This commit is contained in:
rstubryan
2026-01-26 11:45:57 +07:00
parent 40eaa729ef
commit e9238e2bb5
@@ -1,6 +1,6 @@
'use client';
import { ChangeEventHandler, useEffect, useState } from 'react';
import { ChangeEventHandler, useEffect, useRef, useState } from 'react';
import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast';
@@ -22,6 +22,7 @@ import { ProductCategoryApi } from '@/services/api/master-data';
import { cn } from '@/lib/helper';
import { isResponseError, isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { useUiStore } from '@/stores/ui/ui.store';
import { ROWS_OPTIONS } from '@/config/constant';
const RowOptionsMenu = ({
@@ -80,6 +81,9 @@ const RowOptionsMenu = ({
};
const ProductCategoryTable = () => {
const { searchValue, setSearchValue, resetSearchValue } = useUiStore();
const previousPathRef = useRef<string | null>(null);
const {
state: tableFilterState,
updateFilter,
@@ -87,7 +91,7 @@ const ProductCategoryTable = () => {
setPageSize,
toQueryString: getTableFilterQueryString,
} = useTableFilter({
initial: { search: '', nameSort: '' },
initial: { search: searchValue, nameSort: '' },
paramMap: { page: 'page', pageSize: 'limit', nameSort: 'sort_name' },
});
@@ -188,6 +192,7 @@ const ProductCategoryTable = () => {
};
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => {
setSearchValue(e.target.value);
updateFilter('search', e.target.value);
};
@@ -196,6 +201,28 @@ const ProductCategoryTable = () => {
setPageSize(newVal.value as number);
};
useEffect(() => {
// Store current path on mount
previousPathRef.current = window.location.pathname;
return () => {
const currentPath = window.location.pathname;
// if both paths are within /master-data/product-category module
const isCurrentPathProductCategory = currentPath.includes(
'/master-data/product-category'
);
const isPreviousPathProductCategory = previousPathRef.current?.includes(
'/master-data/product-category'
);
// reset if we outside product category module entirely
if (isPreviousPathProductCategory && !isCurrentPathProductCategory) {
resetSearchValue();
}
};
}, [resetSearchValue]);
useEffect(() => {
const isNameSorted = sorting.find((sortItem) => sortItem.id === 'name');
if (!isNameSorted) {