Reputation: 29
I'm trying to return a tiny chunk of code in my main return for a component that is timed. In my return, I want to have the myFunction divs shown after awaiting 5 secs(if the condition is met), but it seems to only display an error. I looked at the react documentation, and it seems you can indeed call a function to return html/jsx, so I'm not sure what I'm doing wrong. Here is my code for this area:
function myFunction(){
return (
<div className="error-container">
<h1>Oops!</h1>
<h2>I ate the page you're looking for</h2>
<img className="errorImage" src={ErrorImage} alt= 'website error' />
<Link to='/'><button className="errorButton"> Back to Home </button></Link>
</div>
);
}
const add5SecondsDelay = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve(myFunction());
}, 50000);
});
}
async function asyncFunctionCall() {
const result = await add5SecondsDelay ();
}
return (
<div className="detail-container">
{(() => {
if(!item.name){
return (
<div>
{asyncFunctionCall()}
</div>
)
} else{
I am still new to these sort of things, so I might be messing up my promise or something. I just can't figure out how to make it return my HTML/JSX after 5 seconds.
Upvotes: 0
Views: 1262
Reputation: 119
You could use useEffect hook to wait those 5 seconds and change the state of a variable, then in your return just do something like this:
import React, { useState, useEffect } from 'react';
const MyDiv = () => (<div>Hi</div>)
const YourComponent = () => {
const [isDivVisible , setIsDivVisible ] = useState(false)
useEffect(() => {
const timer = setTimeout(() => {
setIsDivVisible(true)
console.log('5 seconds later')
}, 5000);
return () => clearTimeout(timer);
}, []);
return isDivVisible ? <MyDiv/> : <div>Loading</div>
}
check this pen: https://codepen.io/ealipio/pen/yLYJvVW?editors=0010
Upvotes: 2