title: How to asynchronously retrieve realtime firebase data in JS?
body: <p>so basically i've been doing a chat app in react.js and I reached that level where I'm not always receiving the data from the database, sometimes i receive it and sometimes not, and the state doesn't always gets updated, what can I do ?</p>
  <pre><code>import { Segment, Comment } from 'semantic-ui-react';
  import MessageForm from './MessagesForm';
  import MessagesHeader from './MessagesHeader';
  import firebase from '../../firebase'
  import { useSelector } from 'react-redux';
  import Message from './Message';
  
  const Messages = () =&gt; {
    const [messagesRef, setMessagesRef] = useState(firebase.database().ref('messages'));
    const [messages, setMessages] = useState([]);
    const [messagesLoading, setMessagesLoading] = useState(true);
    const {currentChannel} = useSelector(state =&gt; state.channel);
    const {currentUser} = useSelector(state =&gt; state.user);
    
  
    const addListeners = channelId =&gt;{
      addMessageListeners(channelId);
    }
  
    const addMessageListeners = channelId =&gt;{
      let loadedMessages = [];
      messagesRef.on('child_added', (snapshot) =&gt; {
        loadedMessages.push(snapshot.val())
        setMessages(loadedMessages);
      })
    }
  
  
  
  useEffect(() =&gt; {
      if(currentChannel &amp;&amp; currentUser){
      addListeners(currentChannel.id);
      }
    }, [])
  
  
    
    const displayMessages = messages =&gt;{
      messages.length &gt; 0 &amp;&amp; messages.map(message =&gt; (
        &lt;Message key={message.timestamp} message={message} user={currentUser} /&gt;
      ))
    }
  
    return (
      &lt;&gt;
      &lt;MessagesHeader /&gt;
      &lt;Segment&gt;
        &lt;Comment.Group className='message'&gt;
          {displayMessages(messages)}
          
        &lt;/Comment.Group&gt;
      &lt;/Segment&gt;
  
      &lt;MessageForm  messagesRef={messagesRef}/&gt;
      &lt;/&gt;
    )
  }
  
  export default Messages;
  </code></pre>