Reputation: 724
I have a mini-app that consists of a search bar and a table with data. The data is searchable using the search bar. I am using lodash debounce to filter the table data when a user enters something in the search bar. So far so good. The problem arises when the search word is erased by pressing the backspace. I want the table to restore the initial data when no input is entered or input is erased.
type IType = {company: string, city: string, domain: string}
export const App: React.FC = () => {
const [userInput, setUserInput] = useState<string>('');
const [tableData, setTableData] = useState<IType[]>(data);
const filterTable = ()=>{
const filteredData = tableData.filter((data)=>data.company.toLowerCase().includes(userInput)
|| data.city.toLowerCase().includes(userInput)
|| data.domain.toLowerCase().includes(userInput));
// eslint-disable-next-line no-console
console.log('filteredData', filteredData);
filteredData.length === data.length ? setTableData([...data]) : setTableData([...filteredData]);
};
const debouncedData = useCallback(debounce(filterTable, 1000), [userInput]);
useEffect(() => {
debouncedData();
}, [userInput]);
const onChangeHandler:
(event: React.ChangeEvent<HTMLInputElement>) => void = (event) => setUserInput(event.target.value);
return (
<div style={mainWrapper}>
<SearchBar userInput={userInput} onChangeHandler={onChangeHandler} />
<Table tableData={tableData}/>
</div>
);
}
;
Upvotes: 1
Views: 704
Reputation: 2165
You can do the conditional rendering
.
If the search input is empty string, just display the original data
and not the computed tableData
.
type IType = {company: string, city: string, domain: string}
export const App: React.FC = () => {
const [userInput, setUserInput] = useState<string>('');
const [tableData, setTableData] = useState<IType[]>(data);
const filterTable = ()=>{
const filteredData = tableData.filter((data)=>data.company.toLowerCase().includes(userInput)
|| data.city.toLowerCase().includes(userInput)
|| data.domain.toLowerCase().includes(userInput));
// eslint-disable-next-line no-console
console.log('filteredData', filteredData);
filteredData.length === data.length ? setTableData([...data]) : setTableData([...filteredData]);
};
const debouncedData = useCallback(debounce(filterTable, 1000), [userInput]);
useEffect(() => {
debouncedData();
}, [userInput]);
const onChangeHandler:
(event: React.ChangeEvent<HTMLInputElement>) => void = (event) => setUserInput(event.target.value);
return (
<div style={mainWrapper}>
<SearchBar userInput={userInput} onChangeHandler={onChangeHandler} />
<Table tableData={userInput === "" ? data : tableData}/>
</div>
Upvotes: 1