Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
14
rated 0 times [  18] [ 4]  / answers: 1 / hits: 12841  / 4 Years ago, sat, march 28, 2020, 12:00:00

I have a simple functional component where i click a button and it is shown, i am trying to get my imported spinner to show for 2 seconds when the button is clicked and then show my imported component after the two seconds, however i am only able to get the spinner to show 2 seconds after the button is clicked and cannot get it to stop



import React, { useState } from react;
import Hello from ./Hello;
import Spinner from '../Spinner/Spinner'
import ./styles.css;

export default function App() {
const [show, setShow] = useState(false);
const [loading, setLoading] = useState(false);

const helloHandeler = () => {
setTimeout(() => {
setLoading(!loading)
}, 2000)
setShow(!show);
};

if (loading) return <Spinner />

return (
<div className=App>
<h1>Adding a Spinner</h1>
<div className=bodyContainer>
{!show && <button onClick={helloHandeler}>Click me</button>}
{show && <Hello />}
</div>
</div>
);
}


Working example can be found here: https://codesandbox.io/s/gallant-engelbart-y3jus


More From » reactjs

 Answers
2

When you trigger helloHandeler() it is registering the setTimeout() to start only after two seconds! This is the behaviour of setTimeout().



Instead, you should setLoading() imediatly, and then setTimeout to stop loading 2sec after. Maybe you would want to setShow() after the two sec also, so place it inside the setTimeout().



update



Also, remmember that JS works asynchronusly, so, when you register setTimeout, the loading is not true yet.



  const helloHandeler = () => {
setLoading(true)
setTimeout(() => {
setLoading(false)
setShow(!show);
}, 2000)

};

[#4342] Thursday, March 26, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josefn

Total Points: 251
Total Questions: 93
Total Answers: 84

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;