0

The state value is not being updated inside the callback function. It always shows the initial value instead of the updated value. However, I need to access the updated state values. How can I achieve this?

here I used directline npm package

directLine.activity$
  .filter((activity) => activity.type === 'message')
  .subscribe((message) => {
    setCurrentMessage(message)
    // current message not having updated value
    currentMessage === message &&
      dispatchMiddleware({
        payload: {
          message_type: 'MESSAGE',
        },
        type: 'MWD_CONVERSATIONS_FROM_WEB_SOCKET',
      })
  })

Hao-Jung Hsieh
  • 516
  • 4
  • 9
Nandha
  • 37
  • 5
  • Because setCurrentMessage is async. It goes to the next line while updating. That's why current message value is not set. You can use useRef() and currentMessage.current. – Hazik Arshad May 16 '23 at 05:46
  • Although it's not updated, if the state can be updated, isn't it always the same value since you set the value before the checking? – Hao-Jung Hsieh May 16 '23 at 06:12
  • Use `message` instead of `currentMessage`. You already have access to the new structure via the `message` variable, why not use it? The state change is queued and will only happen after the current "task"/code finishes. `currentMessage` will contain the new value on the next render. – 3limin4t0r May 16 '23 at 13:40
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – 3limin4t0r May 16 '23 at 13:40

0 Answers0