Created
November 29, 2024 06:16
-
-
Save vicalloy/ea058c36642d241e132f8758ea6671d9 to your computer and use it in GitHub Desktop.
boxes and useEffect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from 'react'; | |
interface ChatProps { | |
idx: number; | |
} | |
async function wait(sec: number): Promise<void> { | |
return new Promise((resolve) => { | |
setTimeout(resolve, sec * 1000); | |
}); | |
} | |
const Box: React.FC<ChatProps> = ({ idx }) => { | |
const [message, setMessage] = useState<string>(`${idx} loading...`); | |
useEffect(() => { | |
(async () => { | |
await wait(1); | |
const newMessage = `${idx * 3} message`; | |
setMessage(newMessage); | |
})(); | |
}, [idx]); | |
return (<div> {message} </div>) | |
}; | |
let count = 0; | |
function App() { | |
const [boxes, setBoxes] = useState<React.ReactElement[]>([]); | |
const [flag, setFlag] = useState(true); | |
const addBox = (): void => { | |
setBoxes([...boxes, <Box idx={count++} />]); | |
} | |
return ( | |
<div className="App"> | |
<button onClick={addBox}>add</button> | |
<button onClick={() => setFlag(!flag)}>toggle</button> | |
{flag?boxes:""} | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment