It re-renders because you are passing through props the search form state, and when you change that state (typing in the search form) the component re-renders and execute all the if
statement you have inside it, so it run's the setData
function triggering another re-render because you change the internal state of that component and then start an infinite loop of renders because every time it enters to the if
statements it runs the setData
function with a different array argument (remember JavaScript treats all none basic types by references so every time data.filter()
executes, it may return same array a similar array but its other reference, so for JavaScript its not the same array).
To fix this you can put all if statements inside other useEffect
hook like this:
useEffect(() => {
// If statemenst
if (
props.formik.values.projectName !== undefined &&
props.formik.values.projectName !== null &&
props.formik.values.projectName !== ""
) {
setData(data.filter((employeeProject) => employeeProject.projectName));
}
if (
props.formik.values.projectType !== undefined &&
props.formik.values.projectType !== null &&
props.formik.values.projectType !== ""
) {
setData(data.filter((employeeProject) => employeeProject.projectType));
}
}, [props.formik.values.projectName, props.formik.values.projectType])
Aldo this code fix the error, will not work as intended because, it will filter the list, and when you get an empty list there is no way it fill again, so the grid will remain empty until you refresh the page manually, so you should filter the list on the JSX without changing the state/list like:
export default function EmployeeProjects(props: any) {
const [data, setData] = useState<EmployeeProject[]>([]);
useEffect(() => {
let employeeProjects: EmployeeProject[] = [];
employeeProjects.push(new EmployeeProject(1, "React", "Frontend"));
employeeProjects.push(new EmployeeProject(2, "Angular", "Frontend"));
employeeProjects.push(new EmployeeProject(3, "Vue", "Frontend"));
employeeProjects.push(new EmployeeProject(4, "Java", "Backend"));
employeeProjects.push(new EmployeeProject(5, "C#", "Backend"));
employeeProjects.push(new EmployeeProject(6, "Python", "Backend"));
setData(employeeProjects);
}, []);
return (
<div style={{ marginTop: "20px" }}>
<DataGrid
autoHeight={true}
columns={[
{ field: "id", headerName: "ID", flex: 200 },
{ field: "projectName", headerName: "Project Name", flex: 200 },
{ field: "projectType", headerName: "Project Type", flex: 200 }
]}
rows={data.filter(
(employeeProject) =>
employeeProject.projectName.includes(
props.formik.values.projectName
) ||
employeeProject.projectName.includes(
props.formik.values.projectType
)
)}
/>
</div>
);
}