0

I am trying to set up a chat page that the user can interact with a chatbot that I have already created. The users messages pop up on the right side of the page but when the message is sent to the server and a response is returned, I am unsure on how to display it on the left side.

const [messages, setMessages] = useState([
    {
      _id: 0,
      text: 'Hello! How may I assist you?',
      createdAt: new Date().getTime(),
      user: {
        _id: 2,
        name: 'System',
        avatar: require('./assets/splash.png')
      }
    },
    {
      _id: 1,
      text: 'New chat started.',
      createdAt: new Date().getTime(),
      system: true
    }
    
  ]);

  function systemResponse(answer){
    <GiftedChat
    
    />
  }
function handleSend(newMessage = []){

    setMessages(GiftedChat.append(messages, newMessage));
    console.log(newMessage);

    var userText = newMessage[0].text;
    console.log(userText);

    fetch('http://ec2-3-23-33-73.us-east-2.compute.amazonaws.com:5000/chatbot',
    {
      method: 'POST',
      body: JSON.stringify({
        textString: userText,
      })
  })
  .then((response) => response.json())
  .then((json) => {<GiftedChat
  user={{_id: 2, name:"System", avatar: require('./assets/splash.png')}}
  text = 'hello' 
  />})
 
}

  return(
    <GiftedChat
    onSend={newMessage => handleSend(newMessage)}
    messages={messages}
    user={{ _id: 1, name: 'Luke' }}
    placeholder="Ask your quesiton here..."
    showUserAvatar
    alwaysShowSend
    scrollToBottom
    />
  );

2 Answers2

0

You can work with User IDs. So if the UserID of the message is the same as your userID then display it on the right. Else display it on the left.

position: item.user._id === user._id ? 'right' : 'left',
Arbnor
  • 2,190
  • 18
  • 26
0

Hi Luke can you show us what your messages array and objects look like as they need to have the right format. If you can update your question with this info i'll update my answer.

For this to work the messages object must contain a user property like:

 {
    _id: 1,
    text: 'Hello developer',
    createdAt: new Date(),
    user: {
      _id: 2,
      name: 'React Native',
      avatar: 'https://placeimg.com/140/140/any',
    },
  },

Then you use the user prop to pass the details of the current user ID. Like:

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

The library contains all of the logic and compares the message id to the user ID. If they are the same the message displays on the opposite side to messages with a different ID.

This info was taken from the documentation React Native Gifted Chat

Your code is parsing a component of GiftedChat to the GiftedChat component when it should only be parsing and object of active user an messages. I have re-written your code.

const [messages, setMessages] = useState([
    {
      _id: 0,
      text: 'Hello! How may I assist you?',
      createdAt: new Date().getTime(),
      user: {
        _id: 2,
        name: 'System',
        avatar: require('./assets/splash.png')
      }
    },
    {
      _id: 1,
      text: 'New chat started.',
      createdAt: new Date().getTime(),
      system: true
    }
    
  ]);

function handleSend(newMessage = []){

    setMessages(prevState => [...prevState, newMessage]);
    

    var userText = newMessage[0].text;
    console.log(userText);

    fetch('http://ec2-3-23-33-73.us-east-2.compute.amazonaws.com:5000/chatbot',
    {
      method: 'POST',
      body: JSON.stringify({
        textString: userText,
      })
  })
  .then((response) => response.json())
  .then((json) => {
    setMessages(prevState => [...prevSate, {
      _id: 3,
      text: 'Hello',
      createdAt: new Date().getTime(),
      system: true
   }
  })
 
}

  return(
    <GiftedChat
    onSend={newMessage => handleSend(newMessage)}
    messages={messages}
    user={{ _id: 1, name: 'Luke' }}
    placeholder="Ask your quesiton here..."
    showUserAvatar
    alwaysShowSend
    scrollToBottom
    />
  );

I don't have time to test this right now but this should work. You only need one instance of gifted chat. With each new message you should update the state of the messages which will re-render the chat with the new messages

Will T
  • 647
  • 5
  • 16
  • Thanks for your help, I have updated my code to include the message array. I am still having trouble understanding how to display a message that is coming from the chatbot I have set up. I can send the message but cannot get a response because doesn't allow me to set up two user id's within the return() ' – Luke Meads Nov 21 '20 at 22:44
  • Hey Luke in your example I see that the message user id is 2 however in the user prop in gifted chat you are parsing 1, This means the user wont match so it will appear on the left. If the user id === message user id then the message appears on the right. I believe all system messages appear on the left – Will T Nov 22 '20 at 06:42
  • When I set the user id to 2, messages show up on the left side and when I have the user id set to 1 it shows up on the right side. My problem is I'm not sure how to write the chatbot's response after the user sends a message. It throws an error when I try to have use two instances of Giftedchat – Luke Meads Nov 22 '20 at 21:25
  • Ah ok, I understand. You need to remove your other instances of gifted chat and put all the messages in a single component. I will update my answer. – Will T Nov 22 '20 at 23:19