✅ – dk.dv – 17-33 Jan 20
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?9 Replies
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
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
well you'd know if the socket is already connected because you've stored the connected socket on the ref
or what not
or as a function component
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
it's only an issue if you want it to trigger a re-render when it changes
right. I can do that with the ws specific functions I think. thanks again!
Solution
np
This question has an answer! Thank you for helping 😄
If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/902647189120118794/1066047918932500522
This thread hasn’t had any activity in 12 hours, so it’s now locked.
Threads are closed automatically after 12 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/902647189120118794/1066047918932500522
Question not getting answered? Maybe it's hard to answer, or maybe you asked at a slow time. Check out these resources for help asking a good question:
https://stackoverflow.com/help/how-to-ask
http://wp.me/p2oIwo-26