Created
September 4, 2019 06:51
-
-
Save beardlessman/0ecb2f6be9beb68ff6a426517376ccd2 to your computer and use it in GitHub Desktop.
custom hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from 'react'; | |
function useFriendStatus(friendID) { | |
const [isOnline, setIsOnline] = useState(null); | |
function handleStatusChange(status) { | |
setIsOnline(status.isOnline); | |
} | |
useEffect(() => { | |
ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange); | |
return () => { | |
ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange); | |
}; | |
}); | |
return isOnline; | |
} | |
function FriendStatus(props) { | |
const isOnline = useFriendStatus(props.friend.id); | |
if (isOnline === null) { | |
return 'Loading...'; | |
} | |
return isOnline ? 'Online' : 'Offline'; | |
} | |
function FriendListItem(props) { | |
const isOnline = useFriendStatus(props.friend.id); | |
return <li style={{ color: isOnline ? 'green' : 'black' }}>{props.friend.name}</li>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment