From ed42282bee1d7f9fd02fcfc43a6ceedfc50e933e Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Thu, 11 Jul 2024 12:00:02 +0200 Subject: [PATCH] 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. --- src/app.jsx | 43 ++++++++++++++++++++----------------------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/src/app.jsx b/src/app.jsx index 6cf4d7b..06bcf00 100644 --- a/src/app.jsx +++ b/src/app.jsx @@ -17,7 +17,7 @@ * along with Cockpit; If not, see . */ -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 ( - - Starter Kit - - - - - ); - } -} + return ( + + Starter Kit + + + + + ); +};