Home > other >  What does `GiftedChat.append` from react-native-gifted-chat do?
What does `GiftedChat.append` from react-native-gifted-chat do?

Time:07-26

In the documentation it does not talk about the method append. What does it do exactly?

Here is an example on how its usage is suggested by the documentation.

setMessages(previousArr => GiftedChat.append(previousArr, message));

CodePudding user response:

Luckily, we can check the source code of GiftedChat:

static append<TMessage extends IMessage>(
    currentMessages: TMessage[] = [],
    messages: TMessage[],
    inverted = true,
  ) {
    if (!Array.isArray(messages)) {
      messages = [messages]
    }
    return inverted
      ? messages.concat(currentMessages)
      : currentMessages.concat(messages)
  }

It appears that the function does what its name suggests. It appends messages to currentMessages by using concat. Since the default value for inverted is set to true, it adds messages to the end of currentMessages, thus messages are supposed to have a newer timestamp than currentMessages. We would expect this to happen from a chat application.

Its usage is straight forward and actually documented in the official example on their GitHub page.

Here is the necessary snippet.

const onSend = useCallback((messages = []) => {
    setMessages(previousMessages => GiftedChat.append(previousMessages, messages))
  }, [])

  return (
    <GiftedChat
      messages={messages}
      onSend={messages => onSend(messages)}
      user={{
        _id: 1,
      }}
    />
  )

GiftedChat manages an internal array of messages. In order to provide an API to your application, i.e. to allow you to manage messages in your own states, it returns the full message array after appending new messages.

  • Related