Can I clean up this code?
Unanswered
Knopper gall posted this in #help-forum
Knopper gallOP
I'm not the strongest React/Next.JS dev, so I'm trying to get good practices in early, before I develop any bad habits.
Could I get suggestions to clean up this code (it's really short), or other ways to do it? Thanks!
page.tsx (all a client rn for testing, individual components would be client in practice)
Could I get suggestions to clean up this code (it's really short), or other ways to do it? Thanks!
page.tsx (all a client rn for testing, individual components would be client in practice)
"use client";
import { ReloadIcon, PlayIcon, StopIcon } from "@radix-ui/react-icons";
import { Button } from "@/components/ui/button";
import { handleStartStopProcess, isProcessRunning } from "@/actions/ProcessManager";
import { useTransition, useState, useEffect } from "react";
export default function Home() {
const [isPending, startTransition] = useTransition();
const [isRunning, setIsRunning] = useState(false);
const [controlsEnabled, setControlsEnabled] = useState(false);
useEffect(() => {
isProcessRunning()
.then(setIsRunning)
.then(() => setControlsEnabled(true));
}, []);
return (
<main className="m-2">
<Button
variant={isRunning ? "destructive" : "success"}
onClick={() => startTransition(async () => {
handleStartStopProcess(isRunning).then(setIsRunning);
})}
disabled={isPending || !controlsEnabled}
>
{isPending ? <>
<ReloadIcon className="mr-2 animate-spin"/> Please wait
</> : <>
{isRunning ? <>
<StopIcon className="mr-2"/> Stop
</> : <>
<PlayIcon className="mr-2"/> Start
</>}
</>}
</Button>
</main>
);
}1 Reply
Knopper gallOP
@/actions/ProcessManager.tsx
I just feel my method of doing the button states in page.tsx could be a lot better / easier to read, but I can't figure out how to do so
"use server";
import { Subprocess } from "bun";
export const handleStartStopProcess = (isRunning: boolean) => isRunning ? stopProcess() : startProcess();
export const isProcessRunning = async () => !!appProcess;
let appProcess: Subprocess | null = null;
async function startProcess() {
if (appProcess) return true;
appProcess = Bun.spawn({
cmd: ["bun", "run", "."],
cwd: "bot",
stdio: ["inherit", "inherit", "inherit"],
});
return true;
}
async function stopProcess() {
if (!appProcess) return false;
appProcess.kill("SIGINT");
appProcess = null;
return false;
}I just feel my method of doing the button states in page.tsx could be a lot better / easier to read, but I can't figure out how to do so