Last active
August 18, 2020 21:52
-
-
Save kedoska/8abc9859d81d220e8e963a1c327ffcd9 to your computer and use it in GitHub Desktop.
A mini reactemoji-monitor
This file contains hidden or 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, { FunctionComponent, useReducer, useEffect } from 'react' | |
export interface MonitorProps { | |
url: string | |
active: boolean | |
interval?: number | |
} | |
export interface MonitorState { | |
pinging: boolean | |
pinged: boolean | |
ok: boolean | |
status: number | |
} | |
export const getDefaultState = (): MonitorState => ({ | |
pinging: false, | |
pinged: false, | |
ok: false, | |
status: 0, | |
}) | |
export type ActionType = { | |
type: 'PING_STARTED' | 'PING_ENDED' | |
ok?: boolean | |
status?: number | |
} | |
export const reducer = ( | |
state: MonitorState, | |
action: ActionType | |
): MonitorState => { | |
switch (action.type) { | |
case 'PING_STARTED': | |
return { ...state, pinging: true } | |
case 'PING_ENDED': | |
const { ok = false, status = 0 } = action | |
return { ...state, pinging: false, pinged: true, ok, status } | |
default: | |
return state | |
} | |
} | |
export const Monitor: FunctionComponent<MonitorProps> = ({ | |
url, | |
interval = 30000, | |
active = false, | |
}) => { | |
const [state, dispatch] = useReducer(reducer, getDefaultState()) | |
useEffect(() => { | |
const timer = setTimeout(async () => { | |
if (!active) { | |
return | |
} | |
try { | |
dispatch({ type: 'PING_STARTED' }) | |
const { ok, status } = await fetch(url) | |
dispatch({ type: 'PING_ENDED', ok, status }) | |
} catch ({ message }) { | |
dispatch({ type: 'PING_ENDED', ok: false, status: 0 }) | |
} | |
}, interval) | |
return () => clearTimeout(timer) | |
}) | |
if (!active) { | |
return <>β</> | |
} | |
if (!state.pinged) { | |
return <>β</> | |
} | |
if (state.pinging) { | |
return <>β</> | |
} | |
if (!state.ok) { | |
return <>π΄</> | |
} else { | |
return <>π’</> | |
} | |
} |
Author
kedoska
commented
Aug 18, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment