R
Reactiflux

✅ – dk.dv – 17-33 Jan 20

✅ – dk.dv – 17-33 Jan 20

Ddkdv1/20/2023
Hi, beginner here, got an issue that probably has a simple solution but I'm not sure how to proceed: In strict mode, all my components mount twice. In my main component, in componentDidMount(), I have a call to connect to a websocket server. This causes the app (in dev mode) to create two identical connections at the start. Normally, I'd just set a variable to check if mount has already been called / if a websocket connection is live, but given these functions are called asynchronously, it doesn't always work reliably. Using state also isn't working because saving state is also async, so even if I try to save a flag, it gets saved after both of the mount operations have already checked for it. Is there a clean way to deal with this?
Solution:
np
Jump to solution
Gghardin1371/20/2023
i'd probably keep the socket on a ref and check if it's already connected before connecting or just ignore the issue as it won't be there in a production build
Ddkdv1/20/2023
hmm. quite new so just reading up on refs. would using that sidestep the whole async issue? I could just ignore the issue or turn off strict mode but I'd prefer to do things the 'right' way - just not sure what the right way is haha
Gghardin1371/20/2023
well you'd know if the socket is already connected because you've stored the connected socket on the ref
class Blah extends Component {
socketRef = React.createRef()

componentDidMount() {
if(!socketRef.current) {
socketRef.current = new Socket(.....)
}
}
}
class Blah extends Component {
socketRef = React.createRef()

componentDidMount() {
if(!socketRef.current) {
socketRef.current = new Socket(.....)
}
}
}
or what not or as a function component
function Blah() {
const socketRef = useRef();

useEffect(() => {
if(!socketRef.current) {
socketRef.current = new Socket(.....)
}

return () => socketRef.current.disconnect();
}, [])
}
function Blah() {
const socketRef = useRef();

useEffect(() => {
if(!socketRef.current) {
socketRef.current = new Socket(.....)
}

return () => socketRef.current.disconnect();
}, [])
}
Ddkdv1/20/2023
oh cool. coming from a jvm background I assumed just creating a variable like that outside 'state' could be an issue with react I'll test this out, thanks a lot
Gghardin1371/20/2023
it's only an issue if you want it to trigger a re-render when it changes
Ddkdv1/20/2023
right. I can do that with the ws specific functions I think. thanks again!
Solution
Gghardin1371/20/2023
np
UUUnknown User1/21/2023
3 Messages Not Public
Sign In & Join Server To View

Looking for more? Join the community!

R
Reactiflux

✅ – dk.dv – 17-33 Jan 20

Join Server