homepage/src/components/roomState.js

57 lines
1.7 KiB
JavaScript

import React, { useEffect, useState } from 'react'
import { StaticImage } from 'gatsby-plugin-image'
const roomStateData = {
loading: { text: '...', color: 'white' },
open: { text: 'offen', color: '#00aa00' },
closed: { text: 'geschlossen', color: '#ee3333' },
error: { text: 'laut API kaputt', color: '#ee3333' },
}
function GetRightImage(openState) {
if(openState === 'loading') {
return <StaticImage src='../images/warning.png' width='250' height='250' alt='...' />
}
if(openState === 'open'){
return <StaticImage src='../images/tuer_offen.png' width='250' height='250' alt='offen' />
}
if(openState === 'closed'){
return <StaticImage src='../images/tuer_zu.png' width='250' height='250' alt='geschlossen' />
}
if(openState === 'error'){
return <StaticImage src='../images/warning.png' width='250' height='250' alt='laut API kaputt' />
}
}
export default function RoomState() {
const [openState, setOpenState] = useState('loading')
useEffect(() => {
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'))
}, [])
const isSSR = typeof window === 'undefined'
const useIMG = false
return (
<a
href="https://status.ctdo.de/"
style={{ color: roomStateData[openState].color }}
>
{isSSR ? '<Benötigt JavaScript>' : useIMG ? GetRightImage(openState) : roomStateData[openState].text}
</a>
)
}