4

I have a react app where I am using socket.io for realtime messaging. I am trying to use common socket object across all react functional components, but in event handler function I am not able to access state objects.

Config:

var socket = io(socketEndPoint)
socket.emit('register', cookies)
export { socket }

ChatComponent:

import {socket} from './Config'
export default function ChatComponent(props) {
  const [chats, setChat] = React.useState([{chat_id: 1234}])
  socket.on('message', (data) => {
    console.log(data)
    console.log(chats)
  })
}

console.log(chats) always prints an empty array.

I tried using Context Api but still not help. Is there any way to access react state. Thanks in advance.

1
  • add here your code Commented Jan 21, 2021 at 19:48

1 Answer 1

6

The answer seems elaborated in this article: https://medium.com/geographit/accessing-react-state-in-event-listeners-with-usestate-and-useref-hooks-8cceee73c559

Which references also this post:

React useState hook event handler using initial state

Update 2021 react functional component

const [chats, setChats] = useState([])

...

socket.on('message', function (messageData) {
    
    setChats((prev) => {
        return [chat, ...prev]
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.