Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useState troubles to update when receiving new events #125

Open
SergeyMelnyk opened this issue Dec 11, 2023 · 2 comments
Open

useState troubles to update when receiving new events #125

SergeyMelnyk opened this issue Dec 11, 2023 · 2 comments

Comments

@SergeyMelnyk
Copy link

Hello everyone, please help with an issue I encountered while using pusher-websocket-react-native. I'm trying to implement a small chat, and the problem is that when I receive a notification in the onEvent method and try to update my local state, the messages value always equals an empty array.

cosnt [messages, setMessages] = useState([])
useEffect(() => {
      getInitialMessagesByRestApi().then(res => {setMessages(res.data)})
}, [])

...
const onEvent = () => {
const onEvent = event => {
    const parsedData = JSON.parse(event.data)

   setMessages([...messages, event.data]) <-- messages in this place always empty
}

I already tried to get initial messages after pusher init, it works but when i am gettig few events like one by one it , messages array always equal to initial without prev message from pusher events

@robsoden
Copy link

I'm also struggling with this. onEvent handlers seem to be completely unaware of any state changes - they only have a snapshot of state when pusher was initiated. This makes it really difficult to do anything useful with events in a modern functional component react native app...

@benw-pusher
Copy link
Contributor

Could you update to setMessages(messages => ([...messages, event.data])); ? With this I was able to see the array being updated correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants