Skip to content

Instantly share code, notes, and snippets.

@SunnyChopper
Created July 4, 2021 00:27
Show Gist options
  • Save SunnyChopper/ce2644bb1974d68638244e9b22a8edbf to your computer and use it in GitHub Desktop.
Save SunnyChopper/ce2644bb1974d68638244e9b22a8edbf to your computer and use it in GitHub Desktop.
Employee Container with `useMemo`
import React, { useEffect, useState, useMemo } from 'react';
import { fetchEmployees } from '../api/employees';
const EmployeeSearchContainer = (props) => {
const [selectedEmployee, setSelectedEmployee] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [searchText, setSearchText] = useState('');
const [employees, setEmployees] = useState([]);
useEffect(() => {
setIsLoading(true);
fetchEmployees().then(employees => {
// For the example, this returns 5k values
setEmployees(employees);
setIsLoading(false);
}).catch(e => {
setIsLoading(false);
});
}, []);
const filteredEmployees = useMemo(() => {
if (searchText && searchText.length > 0) {
return employees.filter(employee => {
if (employee.name.includes(searchText) || employee.email.includes(searchText)) {
return employee.isActive;
} else {
return false;
}
});
} else {
return employees;
}
}, [searchText]);
if (isLoading) {
return 'Loading...';
} else {
return (
<div>
<input type="text" placeholder="Search for Employee" value={searchText} onChange={setSearchText} />
<EmployeesTable employees={filteredEmployees} onSelectEmployee={setSelectedEmployee} />
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment