I would like to create a function where I set the loading state at the beginning to true then do a for loop with timeout functions inside and after the last timeout is finished set the loading state back to false. In my code it is not working because it sets the loading state immediately back to false. My code:
import { useState } from "react"
const Test = () => {
const [loading, setLoading] = useState(false)
const someFunction = async () => {
setLoading(true)
const numArray = [1, 2, 3, 4, 5]
for (let i = 0; i < numArray.length; i++) {
setTimeout(() => {
console.log("do some code")
}, 100)
}
setLoading(false)
}
return (
<button onClick={someFunction} className={`${loading && "text-red-500"}`}>
test
</button>
)
}
export default Test