Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

reactjs - Not able to access react state from socket event handler function

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.

question from:https://stackoverflow.com/questions/65833461/not-able-to-access-react-state-from-socket-event-handler-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...