import React, { useState } from 'react'; import { useHistory, useParams } from 'react-router-dom'; import { makeStyles, Typography, Container, Card, CardContent, RadioGroup, Radio, FormControl, FormControlLabel, Button } from '@material-ui/core'; import MainToolbar from './MainToolbar'; import { useEffectAsync } from './reactHelper'; import { useTranslation } from './LocalizationProvider'; const useStyles = makeStyles((theme) => ({ root: { marginTop: theme.spacing(2), marginBottom: theme.spacing(2), }, buttons: { display: 'flex', justifyContent: 'space-evenly', '& > *': { flexBasis: '33%', }, }, })); const CommandsPage = () => { const classes = useStyles(); const { id } = useParams(); const t = useTranslation(); const history = useHistory(); const [device, setDevice] = useState(); const [commands, setCommands] = useState([]); const [selectedCommand, setSelectedCommand] = useState(); useEffectAsync(async () => { if (id) { let device = undefined; const response = await fetch(`/api/devices?id=${id}`, { headers: { Accept: 'application/json' }, }); if (response.ok) { const items = await response.json(); device = items[0]; setDevice(items[0]); } else { setDevice({}); } if (device) { const response = await fetch(`/api/commands/send?deviceId=${device.id}`, { headers: { Accept: 'application/json' }, }); if (response.ok) { const items = await response.json(); setCommands(items); } else { setCommands([]); } } } }, [id]); const handleSend = async () => { const cmd = commands.find(c => c.id.toString() == selectedCommand); cmd.deviceId = device.id; const response = await fetch(`/api/commands/send`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(cmd), }); if (response.ok) { history.goBack(); } else { console.log ('response!', response); } }; return ( <> {device && ( <> {t('commandSend')} {device.name} {commands && ( setSelectedCommand(event.target.value) }> {commands.map (command => ( } label={command.description} /> ))} history.goBack()}> {t('sharedCancel')} {t('commandSend')} )} > )} > ); } export default CommandsPage;