I am very close to finishing it but something does not click. I pass the async data from another function to useEffect, filter it through switch + .filter and spit it out to UrlParams to be displayed but it does not filter the jobs that are displayed but only changes the URL (example: http://localhost:3001/jobs=null&location=null&since=null&conditions=remote/hybrid). (also after I change URL params it returns an empty array)
If possible can you please add an explanation for me to understand what I was doing wrong with some examples, would be great to learn that way! I will include all the code components here (useState, useEffect, fetch/filter function + jsx)
//useState
const [jobCondition, setJobConditionFilter] = useState('On-site/Remote');
//function + useEffect
const getJobsLocation = useCallback(async (filterCondition) => {
const jobs = await getJobs();
const response = jobs.data.nodes;
const conditionOptions = {
'On-site': 'in_person',
Remote: 'remote',
Hybrid: 'hybrid',
};
const filteredJobs = await response.filter(
(job) => job.jobFilter === conditionOptions[filterCondition],
);
if (!filteredJobs) {
return {};
}
return filteredJobs;
}, []);
useEffect(() => {
getJobsLocation(jobCondition).then((jobs) => {
let condition = jobs;
console.log(condition);
console.log('this is condition log');
switch (jobCondition) {
case 'On-site': condition.filter((con) => con.jobLocation === 'in_person');
break;
case 'Remote': condition.filter((con) => con.jobLocation === 'remote');
break;
case 'Hybrid': condition.filter((con) => con.jobLocation === 'hybrid');
break;
default:
condition = null;
}
if (condition != null) {
const params = new URLSearchParams({
jobs: jobFilter || null,
location: locationFilter || null,
since: datePosted || null,
conditions: jobCondition,
});
history.push({ pathname: '/', search: `${params.toString()}` });
console.log(condition);
console.log('this is condition afterlog');
return;
}
const params = new URLSearchParams({
jobs: jobFilter || null,
location: locationFilter || null,
since: null,
conditions: null,
});
history.push({ pathname: '/', search: `${params.toString()}` });
});
}, [jobCondition, getJobsLocation]);
//JSX
<CustomAutocomplete
sx={{
width: '300px',
marginLeft: '5px',
marginTop: '10px',
}}
placeholder="Location"
value={jobCondition}
setValue={setJobConditionFilter}
options={jobConditionFilter}
endAdornmentIcon={(
<div style={{ marginRight: '15px', marginTop: '-10px' }}>
<ArrowDropDownIcon fontSize="10px" />
</div>
)}
/>
.filter
creates an immutable array object. It does not mutate the array itself.
If you are trying to filter the condition object, you would have to initialise it again.
case 'On-site': {
condition = condition.filter((con) => con.jobLocation === 'in_person')
}
Or, If you want to not mutate the condition object, use jobs array to filter as follows:
let condition = [];
// Inside switch
case 'On-site': {
condition = jobs.filter((job => job.jobLocation === 'in_person')
}