Convert Application to a functional component

This makes properties and state type-safe, i.e. work better for
TypeScript projects.

Also close the file watch properly after the component unmounts. That
should never happen in practice for *this case*, but this is
example/model code, so let's be correct.
This commit is contained in:
Martin Pitt 2024-07-11 12:00:02 +02:00
parent 80c3416270
commit ed42282bee

View file

@ -17,7 +17,7 @@
* along with Cockpit; If not, see <http://www.gnu.org/licenses/>. * along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
*/ */
import React from 'react'; import React, { useEffect, useState } from 'react';
import { Alert } from "@patternfly/react-core/dist/esm/components/Alert/index.js"; import { Alert } from "@patternfly/react-core/dist/esm/components/Alert/index.js";
import { Card, CardBody, CardTitle } from "@patternfly/react-core/dist/esm/components/Card/index.js"; import { Card, CardBody, CardTitle } from "@patternfly/react-core/dist/esm/components/Card/index.js";
@ -25,27 +25,24 @@ import cockpit from 'cockpit';
const _ = cockpit.gettext; const _ = cockpit.gettext;
export class Application extends React.Component { export const Application = () => {
constructor() { const [hostname, setHostname] = useState(_("Unknown"));
super();
this.state = { hostname: _("Unknown") };
cockpit.file('/etc/hostname').watch(content => { useEffect(() => {
this.setState({ hostname: content.trim() }); const hostname = cockpit.file('/etc/hostname');
hostname.watch(content => setHostname(content.trim()));
return hostname.close;
}); });
}
render() {
return ( return (
<Card> <Card>
<CardTitle>Starter Kit</CardTitle> <CardTitle>Starter Kit</CardTitle>
<CardBody> <CardBody>
<Alert <Alert
variant="info" variant="info"
title={ cockpit.format(_("Running on $0"), this.state.hostname) } title={ cockpit.format(_("Running on $0"), hostname) }
/> />
</CardBody> </CardBody>
</Card> </Card>
); );
} };
}