Created
March 4, 2021 15:01
-
-
Save xiaoyunyang/76d687ecaa2fc987edee180658d80d72 to your computer and use it in GitHub Desktop.
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 } 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