'Conditions in useEffect React
I have a useEffect that subscribes to websocket at startup and adds the data that comes from the server to the operationList list. This list is displayed on the webpage. This is a list of operations performed by construction equipment, which I receive online and could not chage on a backend.
useEffect(() => {
const ws = new WebSocket('ws://127.0.0.1:8000/ws/')
ws.addEventListener('message', (e) => {
const response = JSON.parse(e.data)
setOperationsList(operationsList => [
response,
...operationsList,
]);
})
ws.onopen = () => {
ws.send(JSON.stringify({
action: "subscribe_to_operations_activity",
request_id: new Date().getTime(),
}))
}
}, [])
In the same component I have a state, which stores information about the id of the equipment, the report on which is currently displayed on the screen.
const [activeID, setActiveID] = useState(false)
I need to add to the operationsList not all the data that comes in the server, as it is done now response = JSON.parse(e.data). Instead, I need to check the condition response.id == activeID, and to add to operationsList only those data that satisfy the condition. I can't add activeID to the list of useEffect dependencies because in this case, a new WebSocket subscription will be created every time the activeID changes. I understand that most likely I don't understand some basic things, so I would be grateful for any advice
Added the activeID path:
In my component
const [activeID, setActiveID] = useState(false)
const getElementStar = (newID) => {
setActiveID(newID)
}
Then I pass it to child component as props:
<LeftMenu
...
getElementStar={getElementStar}
...
/>
And finally in child component
const getKey = () => {
const newID = props.item.id
props.getElementStar(newID)
}
return (
<ListItemButton sx={{ pl: 4 }} key={props.index} onClick={getKey}>
<ListItemIcon>
{ props.star === props.index ? <Star/> : <StarBorder/> }
</ListItemIcon>
<ListItemText primary={props.item.name} />
</ListItemButton>
);
Solution 1:[1]
You can try running a loop with a condition that, once true, will then push what you want to push to the specific list. That will only work if the data you are receiving from the back-end is a type of array.
let dataList = []
const loopData = () => {
e.data.forEach((obj) => {
if (obj.id === activeID) {
dataList.push(obj)
}
}
}
useEffect(() => loopData(), []);
And then
setOperationsList(...dataList)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
