From 35947778cebed204baea6651e87107d3655ffb9b Mon Sep 17 00:00:00 2001 From: neri Date: Sat, 15 May 2021 19:56:02 +0200 Subject: [PATCH] show error state when room api is not reachable --- src/components/roomState.js | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/src/components/roomState.js b/src/components/roomState.js index e3393e3..7334ed7 100644 --- a/src/components/roomState.js +++ b/src/components/roomState.js @@ -1,21 +1,27 @@ -import React, { useEffect, useState } from "react" +import React, { useEffect, useState } from 'react' const roomStateData = { - loading: { text: "ladeā€¦", color: "white" }, - open: { text: "OFFEN", color: "#00aa00" }, - closed: { text: "GESCHLOSSEN", color: "#ee3333" }, + loading: { text: '...', color: 'white' }, + open: { text: 'offen', color: '#00aa00' }, + closed: { text: 'geschlossen', color: '#ee3333' }, + error: { text: 'laut API kaputt', color: '#ee3333' }, } export default () => { - const [openState, setOpenState] = useState("loading") + const [openState, setOpenState] = useState('loading') useEffect(() => { - async function fetchState() { - const response = await fetch("https://status.ctdo.de/api/simple/v2") - const json = await response.json() - setOpenState(json.state ? "open" : "closed") - } - fetchState() + fetch('https://status.ctdo.de/api/simple/v2') + .then(response => { + if (response.status >= 200 && response.status <= 299) { + return response + } else { + throw new Error() + } + }) + .then(response => response.json()) + .then(json => setOpenState(json.state ? 'open' : 'closed')) + .catch(() => setOpenState('error')) }, []) return (