Toby Toby - 1 month ago 31
React JSX Question

Execute function in stateless component after timeout

I have a loading spinner in a stateless functional component that I'm using while I check for props.

I'd like to use

setTimeout
to have the loading spinner display for 5 seconds and then change the content if props are still not available, but this code doesn't seem to work:

function LoadingIndicator() {
let content = <span>Loading Spinner Here</span>;
setTimeout(() => {
console.log('6 second delay');
content = <span>Page could not be loaded.</span>;
}, 6000);
return (
<div>
{content}
</div>
);
}


I believe this doesn't work because nothing tells react to re-render this component, but I'd prefer not to upgrade to a container if possible.

Answer

Move the timer to the parent. Have the timer change a state value and in its render, pass that state value as a prop to your LoadingIndicator.