Reputation: 191
I am trying to solve a react problem. I followed the below youtube tutorial. I am trying in code sandbox. for some reason the colors of the signal no appearing and its not changing after sometime. I even gave set timeout. Can you let me know how to fix it. Providing my code snippet below.
https://codesandbox.io/p/sandbox/traffic-tkfjl5?file=%2Fsrc%2FApp.tsx%3A19%2C15
https://www.youtube.com/watch?v=plFo3jJRTdE&list=PL6x5Q-Sj_Bla3_wMqhETxMBjFml0XJNPI&index=13
import "./styles.css";
import { useState, useEffect } from "react";
type stopLightState = "stop" | "slow" | "go";
const stop_delay = 3000;
const slow_delay = 2000;
export default function App() {
const [state, setState] = useState<stopLightState>("stop");
function getStopLightClass(light: StopLightState) {
return `light $(light)` + (state === light ? "on" : "");
// stop interpolate
}
useEffect(() => {
if (state === "stop") {
setTimeout(() => setState("go"), stop_delay);
} else if (state === "slow") {
setTimeout(() => setState("slow"), slow_delay);
}
}, [state]);
return (
<div className="stopLight">
{/* <div className={"light stop" + (state === "stop" ? " on" : "")}>here</div> */}
<div className={getStopLightClass("stop")}>here</div>
<div className={getStopLightClass("slow")}>here</div>
<div className={getStopLightClass("go")}>here</div>
</div>
);
}
Upvotes: 1
Views: 81
Reputation: 1
You can find the corrected version in below link: https://codesandbox.io/p/sandbox/traffic-forked-yz8qj6?file=%2Fsrc%2FApp.tsx%3A3%2C1
issues: 1- you didn't handle all the states possible (go, slow, stop) inside useEffect
best practices: 1- take out "light" class because it is a shared class between all divs 2- take a look at use of arrow functions 3- you also can use Enums instead of type here
Upvotes: 0