I am trying to use react hooks and I want to run a function when two things change:
const Filter = ({ orderList, orders }) => {
const [from, setFrom] = useState();
const [to, setTo] = useState();
const [filteredList, setFilteredList] = useState(orders);
useEffect(() => {
const filteredOrders = orders.filter(function(item) {
return item.order_number >= from && item.order_number <= to;
});
setFilteredList(filteredOrders);
console.log(filteredList);
}, [from, to]);
more precisely I would like to filter the array only when BOTH from and to states changes, this is because I am trying to filter an array from some inputs defined by the user.
How can I achieve this?
You would not be able to accomplish this by passing in more arguments into useEffect(), by default that will cause useEffect() to execute as long as one item is changed.
You could however combine useEffect with useRef to accomplish this. We will use useRef to store the previous values of the states and compare that to our new state values.
See codesandbox for example: https://codesandbox.io/s/heuristic-nobel-6ece5
const App = () => {
const [from, setFrom] = useState();
const [to, setTo] = useState();
const previousValues = useRef({ from, to });
useEffect(() => {
if (
previousValues.current.from !== from &&
previousValues.current.to !== to
) {
//your logic here
console.log("both changed")
previousValues.current = { from, to };
}
});
return (
<div>
<input
placeholder="from"
value={from}
onChange={e => setFrom(e.target.value)}
/>
<input
placeholder="to"
value={to}
onChange={e => setTo(e.target.value)}
/>
</div>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With