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 committed by Allison Karlitskaya
parent 6af3331d7a
commit 4bbb291281

View file

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