Skip to content

Instantly share code, notes, and snippets.

@beardlessman
Created September 4, 2019 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beardlessman/0ecb2f6be9beb68ff6a426517376ccd2 to your computer and use it in GitHub Desktop.
Save beardlessman/0ecb2f6be9beb68ff6a426517376ccd2 to your computer and use it in GitHub Desktop.
custom hook
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