Search code examples
reactjsreact-nativereact-statereact-native-gifted-chat

How to update state of messages in react-native-gifted-chat?


I relying on API calls for sending messages using react-native-gifted-chat in a react native app, I want the flow to be like when the user clicks on the send button it should have the state as pending:true and when the API call is a success I want it to have it as pending:false,sent:true I can achieve the first part but even when the API call is a success it does not update the state. Below is my implementation of it, I am trying to follow solution posted [here][1] but I think something is wrong with my implementation, Please let me know if any clarification is required.

function SmsConversations({ route }) {

  const onSend = useCallback((messages = []) => {
    const [messageToSend] = messages;
    messageToSend.pending = true;
    sendSMS(toNumber, fromNumber, messageToSend.text)
      .then((res) => {
        messageToSend.pending = false;
        messageToSend.sent = true;
      })
      .catch((err) => (messageToSend.pending = true))
      .done();
    setMessages((previousMessages) =>
      GiftedChat.append(previousMessages, messageToSend)
    );
  }, []);

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

Also if the API is errored is there a way to handle it using react-native-gifted-chat, like failed or something?


Solution

  • You can append() different messages for loading and error handling.

    for loading --

    you can append message

    setMessages((previousMessages) =>
      GiftedChat.append(previousMessages,{
         pending: true,
         sending: false,
         text: 'Loading...'
    }));
    

    and you can remove loading message by using

    setMessages(previousMessages => {
        let newMessages = [...previousMessages];
        newMessages.shift();
        setTyping(1);
        return GiftedChat.append(newMessages, response)})
    

    for Error Handling you have to append same message with error in catch block and it's done.