简体   繁体   中英

How can I refresh the chatting screen when new messages received?

I'm using my own messages backend with codeigniter, I'm getting the messagesm, and i can send and retreive the new messages back from the server, But I'm not sure how to make UI re-call server and load new messages again? I'think I'm missing some concept here?!

import React, { useState, useCallback, useEffect } from 'react'
import { GiftedChat } from 'react-native-gifted-chat'

export function Example() {
  const [messages, setMessages] = useState([]);

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

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

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

If you want to keep connection between client and server, socket could be a good choice. Your UI can listen to 'message-received-event'. You can refer here:https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM