Jak sprawić, by stan zniknął po pewnym czasie (React)
let timeoutId = null;
export function App(props) {
const [updated, setUpdated] = useState("");
useEffect(() => {
// if there's a message in updated
if(updated.length > 0) {
//remove previous timeout if any
if(timeoutId !== null) {
clearTimeout(timeoutId);
}
// create a timeout to remove it
timeoutId = setTimeout(() => setUpdated(""), 3000);
}
// cleanup
return () => {
if(timeoutId !== null) {
clearTimeout(timeoutId);
}
}
}, [updated])
return (
<div className='App'>
<button onClick={() => setUpdated("You have successfully did something!")}> setUpdated("You have successfully did something!") </button>
<hr />
{updated}
</div>
);
}
SAMER SAEID