I have react app with ticket polling (ticket is part of link for websocket connection). Then I pass websocket object to another component, because only this (another) component should make .send()
After user login or logout I need to get new ticket for new connection because server has specialized data for logged users.
How should I organize my code for this task?
I tried to reassign ws object after login/logout but got "Assignments to the 'ws' variable from inside React Hook useEffect will be lost after each render" error I can't store ws assignment inside useEffect hook because then i not be able to pass it as prop I'm although using Redux as you can see
const App = () => {
const { ticket, isLoggedIn } = useSelector(state => state);
const dispatch = useDispatch();
useEffect(() => {
const requestTicket = () => {
fetch('http://some/api/websocket', {
method: 'POST'
})
.then(response => response.json())
.then(ticket => {
dispatch(setTicket(ticket));
});
};
requestTicket();
}, [dispatch]);
let ws = new WebSocket('ws://socket/' + ticket);
useEffect(() => {
fetch('http://some/api/websocket', {
method: 'POST'
})
.then(response => response.json())
.then(ticket => {
ws = new WebSocket('ws://socket/' + ticket);
});
}, [isLoggedIn, ws]);
ws.onmessage = e => {
dispatch(setData(JSON.parse(e.data)));
};
return <Child ws={ws} />;
};