0

I am doing a multi filter component, which can filter by keyword, category work types and so on... so this is one useEffect Hook, this filters by entering keyword of job titles and job category.

 useEffect(() => {
    const newFilteredJobs = jobs.filter((job) => {
      return (
        job.title.toString().toLocaleLowerCase().includes(searchField) &&
        job.category
          .toString()
          .toLocaleLowerCase()
          .includes(categorySearchField)
      );
    });
    setFilteredJobs(newFilteredJobs);
  }, [jobs, searchField, categorySearchField]);

I would like to filter one more which is work type, however, this requires pass props from child component to parent component.

This is in the parent component

<WorkType jobs={jobs} onFilterJobsByType={filterJobsByTypeHandler} />

This is my filterJobsByTypeHandler function

  const filterJobsByTypeHandler = (jobTypes) => {
    console.log(`selected job types are ${jobTypes}`);
    const newFilteredJobs = jobs.filter((job) => {
      for (let i = 0; i < jobTypes.length; i++) {
        if (job.jobType !== undefined) {
          return job.jobType.toString() === jobTypes[i];
        }
      }
    });
    setFilteredJobs(newFilteredJobs);
  };

I need to select and deselect job types to refresh the filtered jobs, I suppose I need to use useEffect hook? As I can control the dependencies. But i am struggling how I can put the function inside of the useEffect hook.

I tried to use useCallBack Hook, but I could not get the full list of jobs by deselecting the selected work types.

Alex Zhang
  • 13
  • 2

1 Answers1

0

I stored selected jobTypes as state in the Search.jsx.

const [jobTypes, setJobTypes] = useState([]);

And set the jobTypes from the WorkType.jsx by modifying filterJobsByTypeHandler.

const filterJobsByTypeHandler = (_jobTypes) => {
 setJobTypes(_jobTypes)
};

Finally, I added the jobTypes as a dependency array of the useEffect to filter the jobs.

useEffect(() => {
  const newFilteredJobs = jobs.filter((job) => {
    //   console.log(job.country.toString() === selectedCountries.toString());
    let filtered = job.title.toString().toLocaleLowerCase().includes(searchField) &&
      job.category
        .toString()
        .toLocaleLowerCase()
        .includes(categorySearchField)
        //    &&
        // job.country.toString() === selectedCountries.toString()
    if (jobTypes.length) {
      filtered  = filtered && jobTypes.includes(job?.jobType?.[0] || "")
    }
    return filtered;
  });
  setFilteredJobs(newFilteredJobs);
}, [jobs, searchField, categorySearchField, jobTypes]);

Here is the CodeSandbox which contains full code. Hope this would solve your issue.

Bikas Lin
  • 689
  • 5
  • 16