Muhammad
Muhammad

Reputation: 21

How can I use setTimeout to return a JSX element inside an if condition

I am trying to implement a search feature, using custom hooks, and retrieving data from an external API. The problem is that when the user enters an invalid search term, it immediately returns the JSX element inside the if condition. How can I delay showing the JSX element using setTimeout, so first show the user a spinner or something, then redirect them to the previous page. This is what I have:

if (!movies[0])
    return (
        <>
            <Spinner />
            <h1>NO RESULTS FOUND</h1>
        </>
    );

This is what i'd like to do theoretically:

if (!movies[0]) => show Spinner (for 200ms) => setTimeout(show error and redirect after 200ms, 200)

how could I implement this in react?

Upvotes: 0

Views: 555

Answers (1)

VersifiXion
VersifiXion

Reputation: 2282

You can maybe try something like this :

const [loading, setLoading] = useState(true);

useEffect(() => {
  let timer = setTimeout(() => {
    setLoading(false);
  }, 2000);

  return () => { clearTimeout(timer) };
}, [];

return (
  <>
    {loading ? <div>Loading</div> : <div>...<div>}
  </>
);

Upvotes: 1

Related Questions