✅ – 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?
Solution:
np
G
ghardin137454d ago
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
D
dkdv454d ago
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
G
ghardin137454d ago
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();
}, [])
}
D
dkdv454d ago
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
G
ghardin137454d ago
it's only an issue if you want it to trigger a re-render when it changes
D
dkdv454d ago
right. I can do that with the ws specific functions I think. thanks again!
Solution
G
ghardin137454d ago
np
UU
Unknown User453d ago