score:1
so i had a little bit of trouble getting the codesabox to work. i still found the issue though. there's two big issues. original:
const handlechange1 = (e) => {
if (e.target.checked) {
setlearningdirection([...learningdirection, e.target.value]);
} else {
setlearningdirection(
learningdirection.filter((id) => id !== e.target.value)
);
}
if (e.target.checked) {
settargetaudience([...targetaudience, e.target.value]);
} else {
settargetaudience(targetaudience.filter((id) => id !== e.target.value));
}
};
you shouldn't have this all in one function. with the way this works now, each checked input is getting assigned to both filters (which only break the first filter because of the useeffect
). a good rule of thumb to follow is to have each setstate
tied to one function (sometimes that unavoidable, but that's what i would do here). here's what i mean. solution:
const handlelearningdirectionchange = (e) => {
if (e.target.checked) {
setlearningdirection([...learningdirection, e.target.value]);
} else {
setlearningdirection(
learningdirection.filter((id) => id !== e.target.value)
);
}
};
const handletargetaudiencechange = (e) => {
if (e.target.checked) {
settargetaudience([...targetaudience, e.target.value]);
} else {
settargetaudience(targetaudience.filter((id) => id !== e.target.value));
}
};
// todo: change the onchange inside the forms
you also have a 2nd problem inside the useeffect. original:
useeffect(() => {
if (learningdirection.length === 0) {
setfilteredlist(searchlists);
} else {
setfilteredlist(
searchlists.filter((filterlist) =>
learningdirection.some((category) =>
[filterlist.learningdirection].flat().includes(category)
)
)
);
}
if (targetaudience.length === 0) {
setfilteredlist(searchlists);
} else {
setfilteredlist(
searchlists.filter((filterlist2) =>
targetaudience.some((category) =>
[filterlist2.targetaudience].flat().includes(category)
)
)
);
}
}, [learningdirection, targetaudience]);
the 2nd setfilteredlist()
is just going to overrite the first. so the learningdirection
filter isn't doing anything. this fix is a little more messy, but it does work. solution:
(edit: initialize set with searchlists, and change filters to look for deletions. also removed if unnecessary if statements)
useeffect(() => {
const set = new set([...searchlists]);
learningdirection.foreach((direction) => {
searchlists.foreach((item) => {
// change this to "===" if you want the opposite result
if (item.learningdirection !== direction) {
set.delete(item);
}
});
});
targetaudience.foreach((audience) => {
searchlists.foreach((item) => {
// change this to "===" if you want the opposite result
if (item.targetaudience !== audience) {
set.delete(item);
}
});
});
setfilteredlist([...set]);
}, [learningdirection, targetaudience]);
we're using a set
to avoid duplicate values, looping over the checked values, then looping over the searchlist
to get the results. that happens first then we assign the results to the state (using the ... operator so we turn the set into an array).
overall, part of me wants to completely refactor this component. the solutions here should get you up and running to move forward, but i feel as though there's a lot of unnecessary complexity in how you're handling things. i'd have to spend a lot more time trying to understand what's going on to be really sure of that and provide a better alternative though.
edit2: providing two alternatives
my guess is that this is how you want the filters:
// have all the results
const set = new set([...searchlists]);
// remove unselected check boxes (if any are selected)
if (learningdirection.length) {
searchlists.foreach((item) => {
if (!learningdirection.includes(item.learningdirection)) {
set.delete(item);
}
});
}
// remove more unselected check boxes (if any are selected)
if (targetaudience.length) {
searchlists.foreach((item) => {
if (!targetaudience.includes(item.targetaudience)) {
set.delete(item);
}
});
}
setfilteredlist([...set]);
or maybe this?
// start empty if there's any selected checkboxes
const set =
learningdirection.length > 0 || targetaudience.length > 0
? new set()
: new set([...searchlists]);
// add to empty set if any checkboxes are selected
if (learningdirection.length) {
searchlists.foreach((item) => {
if (learningdirection.includes(item.learningdirection)) {
set.add(item);
}
});
}
// add more if any checkboxes are selected
if (targetaudience.length) {
searchlists.foreach((item) => {
if (targetaudience.includes(item.targetaudience)) {
set.add(item);
}
});
}
setfilteredlist([...set]);
Source: stackoverflow.com
Related Query
- ReactJS having issue with checkbox filtering
- issue in checkbox with custom table pagging using reactjs
- Having an issue with e.target.value returning Undefined in React
- caching issue with web application developed using reactjs & webpack
- What is the purpose of having two running ports when we working with ReactJS and NodeJS?
- having an issue creating new react app with create-react-app
- Having an issue while up and running unit test with react redux testing library
- Using Grommet with ReactJS webpack and scss import Issue
- React.js Form input onChange having issue with getDerivedStateFromProps
- ReactJS MobX and react-router v4 issue with url history
- Having a prod build issue with Webpack, React, postCSS, and possibly other JS code being injected properly
- Reactjs Render issue on popover with data fetched from BE
- Issue with adding style to element with reactjs
- Multiple checkbox values handling with ReactJS
- ReactJS rendering issue with edited array
- Having issue with defining path for image in a react application
- How to checkbox filtering in reactjs and handle state? and show the available item after the checkbox
- Checkbox property DefaultChecked in reactjs not working with states updated by radio button
- reactjs for loop is stopping at 1 for some reason and issue with trying to use set state in a loop
- ReactJS with Sockets Nested JSON parsing data issue
- 'this' issue while mapping a List with button reactjs
- Issue with chartjs linear gradient for the mixed bar chart in ReactJS is not calculated for each individual Bars
- ReactJS - synchronization issue with axios.post
- React JS: Having issue with CREATE_REACT_APP when using npx command in VS Code
- Issue with ReactJS Keys
- How to manage checkbox filtering with React?
- ReactJS - issue with rendering the proper component
- ReactJS ES6 Issue with import class
- Not able to resolve issue with api of OpenWeatherApi for fetching weather data of a city using City id using axios in Reactjs
- facing issued with disabling checkbox in reactjs
More Query from same tag
- Package signatures do not match the previously installed version
- react, styled-components - setting props on a imported styled div
- React Router first route with no menu or main layout
- How to render jsx in react with condition true and array mapping?
- Simple To-Do List with React, Array.filter is not working as expected?
- React how to render page after query change in URL
- Why is React.js removing the srcset tag on <img />?
- How to click unrendered virtualized element in TestCafe
- How to add vertical scroll to my React material table?
- Immutable.js - fromJS generate Record in place of Map
- Redux-toolkit: No effect when deleting an item
- Warning: Can't perform a React state update on an unmounted component hooks
- First update of component
- Mock api in react redux-thunk project returning undefined
- my react app contains p5 sketches that keep repeating
- redux saga knowing when task is done
- Can't handlechange in Formik in Reach.Js
- How to get return value from renderHook
- How to update data in MERN stack
- How to Formik setFieldValue in useEffect hook
- React Redux onDeleteClick isNot Function
- how to pull api array from website about covid statistics
- Snackbars not read by screen reader when triggered from a dialog
- Material-UI | Using `theme` in makeStyles
- Change State whenever button is clicked back and forth in React?
- how to listen page url change without page refresh in react?
- UNMET PEER DEPENDENCY react
- Webpack can do multiple entries, how can I do the same thing for resolve.alias?
- validate confirmation password in redux form
- react: element.getBoundingClientRect is not a function