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:
parent
80c3416270
commit
ed42282bee
1 changed files with 20 additions and 23 deletions
43
src/app.jsx
43
src/app.jsx
|
|
@ -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) }
|
||||
/>
|
||||
</CardBody>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Card>
|
||||
<CardTitle>Starter Kit</CardTitle>
|
||||
<CardBody>
|
||||
<Alert
|
||||
variant="info"
|
||||
title={ cockpit.format(_("Running on $0"), hostname) }
|
||||
/>
|
||||
</CardBody>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue