score:1
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"));
},[]);
score:1
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>
);
}
score:1
make it in:
function app() {
const socket = io("http://localhost:3001",
);
useeffect(()=> {}
or use usestate:
function app() {
const [socket, setsocket ] = usestate(null);
);
useeffect(()=> {
setsocket(io("http://localhost:3001"));
}
score:1
you could try to store the socket in a variable state. something like this:
import react, { usestate, useeffect } from "react";
import io from "socket.io-client";
function app() {
const [socket, setsocket] = usestate();
useeffect(() => {
setsocket(io("http://localhost:3001"));
}, []);
function sendsocketdata(socket) {
socket.emit("hello", "world");
}
return (
<div classname="app">
<button onclick={()=>sendsocketdata(socket)}>send data </button>
</div>
);
}
export default app;
Source: stackoverflow.com
Related Query
- How can i access variable inside useEffect() hook
- How can I access a value of a variable inside a map function?
- How can I make useEffect react hook rerender based on a variable value?
- How can I access array built in useEffect hook with React?
- Can I set state inside a useEffect hook
- How to access props from useEffect hook in Reactjs
- How can I access state in an useEffect without re-firing the useEffect?
- Access old state to compare with new state inside useEffect react hook with custom hooks usePrevious
- Invalid hook call. Hooks can only be called inside of the body of a function component when i call useQuery in useEffect
- Can I use the UseEffect hook inside getStaticProps?
- How I can access to DOM node inside of withStyle component?
- Assignments to the 'timeInterval' variable from inside React Hook useEffect will be lost after each render
- How can I make a request to an API based on the response from another request? React Hook "useSwr" cannot be called inside a callback
- How can I access a state hook value from a callback passed to a listener?
- How do I pass a custom parameter to nextjs dynamic route so I can access it inside getInitialProps
- How can I declare a variable inside brackets?
- How can i get access to the current user inside of react from firebase?
- How can stop infinite loop in useeffect hook
- How can I pass a param to a promise inside usePromise React hook
- How can I access another function inside the react Context.Provider value?
- How can I access JSON property of nested object inside object array
- How to refactor a React hook so that I can call it inside a callback?
- How can I access useParams value inside redux selector as ownProps
- How can i access the history object inside of this promise call?
- How to access a variable or a value of a function inside another function
- How to access variable values inside componentWillMount() in reactjs
- How can I render the components after useEffect hook is finished?
- How React hook access closure variable
- How can I access this.state of React component inside of a filter function?
- How can I access a state variable using a string within functional component?
More Query from same tag
- "Warning: react-modal: App element is not defined. Please use `Modal.setAppElement(el)` or set `appElement={el}`"
- react-redux: Getting error 'dispatch is not a function' during 'connect'
- React app gets 404 when fetching url with params
- How to remove data:image/png;base64 in base64 before uploading to api server through axios post in ReactJs
- Text is not updated when I changed my Redux state
- Most ideal way to call firebase getIdToken
- Submit button in a form works after the second click. ReactJS
- Why is my empty object in useState hook rendering?
- React bootstrap - how to make navBar with 100vh height when in mobile
- Setting React hooks state before function call
- Error while creating validations for react-hook-form
- How to add a button inside every row under a particular column in Bootstrap React Table?
- material ui datagrid a status menu in table cell
- Nextjs causing hard refresh when i click in the Link
- how to change the text value back to default when pressed again
- Using Webpack when extending a browser-native class
- Using roles and specific user id to limit what sections can be viewed in react / node / express / mysql?
- React js to refresh page after onClick has been called
- Remove item from object by key
- compare two arrays of Objects in JavaScript and if true save new items to MongoDB
- Problem with testing for error in React component using react-query and axios. Test with React Testing Library, Jest, msw
- Change Value of Object Once Added To Array
- Each child in an array or iterator should have a unique "key" prop. React JS Error
- How to convert html component to pdf print in nuxt js projects - doc.fromHTML true usage
- Mapping array data in react
- redux Form 7.4.2 Server side validation not working with axios , gives error Unhandled Rejection (SubmissionError): Submit Validation Failed
- How do I create a Typography component that can be used as h1, h2, h3, h4..etc
- Reset a react-query useQuery hook to clear data on the rendered page
- Update state when input value doesn't match the pattern
- How to make Modal pop up on only current screen and once per day on react?