Skip to content

Instantly share code, notes, and snippets.

@xiaoyunyang
Created March 4, 2021 15:01
Show Gist options
  • Save xiaoyunyang/76d687ecaa2fc987edee180658d80d72 to your computer and use it in GitHub Desktop.
Save xiaoyunyang/76d687ecaa2fc987edee180658d80d72 to your computer and use it in GitHub Desktop.
import React, { useState } from "react";
const UiState = {
LOADING: "LOADING",
ONLINE: "ONLINE",
OFFLINE: "OFFLINE",
};
const UiStateMessageMap = {
[UiState.LOADING]: "Loading...",
[UiState.ONLINE]: "Online",
[UiState.OFFLINE]: "Offline",
};
const getUiState = (status) => {
const { isOnline } = status;
if (isOnline === null) return UiState.LOADING;
return isOnline ? UiState.ONLINE : UiState.OFFLINE
};
function FriendStatus(props) {
const [uiState, setUiState] = useState(UiState.LOADING); // init state
useEffect(() => {
function handleStatusChange(status) {
const nextUiState = getUiState(status);
setUiState(nextUiState);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
return UiStateMessageMap[uiState];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment