I am new to react and have initialized a variable named socket inside the use effect hook. I am trying to access it in my return statement. However i cant seem to access it. I am not sure how to do it. Thanks in advance!
function SendSocketData(socket) {
socket.emit("hello", "world");
}
function App() {
useEffect(()=> {
let socket = io("http://localhost:3001",
);
},[]);
return (
<div className="App">
<button onClick={()=>SendSocketData(socket)}>Send Data </button>
</div>
);
}
export default App;
You first need to declare the socket object as a variable with useState():
import React, { useState, useEffect } from 'react';
const [socket, setSocket] = useState(null);
Then assign it with useEffect():
useEffect(()=> {
setSocket(io("http://localhost:3001"));
},[]);
you can define the variable outside of the component or declare it inside then function and the assign the value to it inside useEffect.
function SendSocketData(socket) {
socket.emit("hello", "world");
}
let socket;
function App() {
useEffect(()=> {
socket = io("http://localhost:3001",)
}, []);
return (
<div className="App">
<button onClick={()=>SendSocketData(socket)}>Send Data </button>
</div>
);
}
export default App;
OR
function App() {
let socket;
useEffect(()=> {
socket = io("http://localhost:3001",)
}, []);
return (
<div className="App">
<button onClick={()=>SendSocketData(socket)}>Send Data </button>
</div>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With