so I receive data through socket from backend and then I push the data (item) to an array, but If a variable is true (means its paused) I dont want to push the item to the array.
const [sales, setSales] = useState([])
const [paused, setPaused] = useState(false);
const handlePush = (dt) => {
if(paused) return;
let data = dt.itemListed.data
let obj = {
name: dt.itemListed.data.item.metadata.name,
data
}
if (sales.findIndex(i => i.name === dt.itemListed.data.item.metadata.name) > 0) return;
if (sales.length >= 10) sales.pop();
setSales(prevState => [obj, ...prevState])
}
useEffect(() => {
socket.on("itemListed", (dt) => {
handlePush(dt);
})
}, [socket])
The variable paused is set to true, Im already debugging it and I have also a text displaying on the screen saying if its paused or not. Also, the code where I check if the array size is 10 is also not working.
The code was working fine, but then I changed into socket.io-client lib, and it stopped working.
What I think is happening is that the useEffect is being "read" only once and it is ignoring the futures validations and it keeps just pushing the items.
What can I do?
CodePudding user response:
This should fix your issue
useEffect(() => {
socket.on("itemListed", (dt) => {
handlePush(dt);
})
return () => {
socket.off("itemListed") // cleanup
};
}, [socket, handlePush])
Your useEffect is listening on a previous version of handlePush that uses the old pause
value, so that's why it still able to push.
If you add the function handlePush
as a dependency for useEffect it would re-run every time handlePush changes so you would have the latest function.
For performance, you should also utilize the useCallback()
hook on the handlePush()
function.