Skip to content

useChat's messages does not trigger an update as a dependency in a useCallback, which is called inside of onFinish(...) #548

@davit-b

Description

@davit-b

Simply put

const {
    messages,
    setMessages,
    input,
    setInput,
    append
  } = useChat({
    onFinish: (message) => {
      pushToLocalStateAndReset()
    }
  })
  const pushToLocalStateAndReset = useCallback(() => {
    console.log({
      msg: 'pushToLocalStateAndReset',
      messages: messages,
    })
  }, [messages])

On the first chat will output
Screenshot 2023-09-07 at 12 56 49 PM

Even though there is data within the messages[] array as it's render on the screen.

The problem

It's likely one of two things

  1. I'm using useCallback incorrectly because of my lack of experience with React.
  2. Something about the way that SWR implements messages and it's mutate(...) function doesn't work like if messages was simply stored inside of useState for warning dependency that an update has occured.

See

const { data: messages, mutate } = useSWR<Message[]>([api, chatId], null, {

  // Store the chat state in SWR, using the chatId as the key to share states.
  const { data: messages, mutate } = useSWR<Message[]>([api, chatId], null, {
    fallbackData: initialMessages,
  });

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions