I have the following line of code. Without setTimeout, things working properly. When I enable, setTimeout, there is no output.
What I am doing wrong?
const PrintBox = ({posts,maximise,data}) => {
if ((posts)&& posts.postType === "printplease"
{
setTimeout(function(){
return <div>
<h1>PrintPlease <h1>
</div>
},6000);
}
Real world code looks very similar to this. The timing of each post depends on the current post (it changes for every post..)
const PrintBox = ({posts, maximise}) => {
if ((posts)&& posts.postType === "printplease"
{
setTimeout(function(){
<div >
{(maximise === false)?
(<div className="outerbox">
<div>
<div
className="container"
>
<Printbox
data ={data}
maximise ={maximise}
/>
</div>
</div>
</div>
):(<div className="outerbox outexpand"><div className= "container container-extend"
>
<Printbox
data ={data}
maximise ={maximise}
/>
</div></div>)}
</div>
</div>
},post.timing);
}
``
CodePudding user response:
You can use the bool flag to achieve this. have a look at this code
import React ,{useState , useEffect} from 'react'
export default const Component = () =>{
const [canShow , SetCanShow] = useState(false)
// Set Time out
useEffect(()=>{
const timer = setTimeout(function() {
SetCanShow(true)
}, 1000)
return () => {
clearTimeout(timer);
};
})
return (
{canShow ? <h1> visible </h1> : <> </>}
)
}
CodePudding user response:
Due to how React works internally, It's recommended to use hook optimized for React render cycles.
import { useEffect, useRef, useState } from "react";
function useTimeout(callback, delay) {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
const id = setTimeout(tick, delay);
return () => clearTimeout(id);
}
}, [delay]);
}
export default function App() {
const [isIdle, setIdle] = useState(true);
useTimeout(() => setIdle(false), 1000 * 3);
return <div>{isIdle ? "Waiting..." : "Ready to print"}</div>;
}
Demo preview - https://codesandbox.io/s/xenodochial-wildflower-6r9e5g?file=/src/App.js:0-663