'Not Able to access my context value inside Socket.on() in React js
I am creating one to one chat app in react js with the help of socket.io but the problem is that i am not able to access my context value inside my socket.on() but i can access my context value outside socket.on() I don't know why this is happening, my code is very huge and so i am sharing this small code for solution.
const { state, dispatch } = useStore()
useEffect(() => {
dispatch({ type: "SOCKET_CONNECTION", payload: socket })
socket.on("all_connected_users", (user) => {
dispatch({ type: "ALL_USERS", payload: user })
})
socket.on("new_message", (data) => {
const key = sortNames(data.senderName, data.receiverName)
if (selectedUserRef.current === data.senderName) {
data.isSeen = true
}
if (key in checkMessageRef.current) {
dispatch({ type: "PUSH_MESSAGE", payload: { key, data } })
} else {
dispatch({ type: "ADD_MESSAGE", payload: { key, data } })
}
})
}, [])
i am not able to access my state.selectedUser and state.allMessages so i am using here useRef() and storing my context value inside useRef() for access that values inside socket.on() please explain my why this is happening
thanks in advance and sorry for my english
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
