Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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