Search code examples
javascriptreactjssettimeout

react add setTimeout to loading


I am using react to fetch data and show it in my app . If I am loading , I display the message : "Loading ..." .

What I want is to use setTimeout() to show the loading message for a few more seconds than it should be . However I do not know how to write this in react .

My code :

export default function JobList() {
  
  const {loading ,error , jobs} = useFetch();
  

  return (
    <div>
      {loading && <p> Loading  </p>} //HOW DO I USE SETTIMEOUT ON THIS <P> ELEMENT ? 
      {jobs && jobs.map(j=>return <p> {j.title} </p>)}
    </div>  
  );
  
} 

Solution

  • export default function JobList() {
      const [isLoading, setIsLoading] = useState(false)
      const {loading ,error , jobs} = useFetch();
    
      useEffect(() => {
        if (loading) {
          setIsLoading(true)
        }
    
        if (!loading) {
          setTimeout(() => {
            setIsLoading(false)
          }, 2000)
        }
      }, [loading])
    
      return (
        <div>
          {isLoading && <p> Loading  </p>}
          {!isLoading && jobs?.map(j=>return <p> {j.title} </p>)}
        </div>  
      );
    } 
    

    Create a state called isLoading with useState hook. Use that to conditionally render the Loading component/spinner.

    setIsLoading is called in useEffect everytime loading changes. So, if you add the setTimeout in useEffect it will change from true to false after 2000 milliseconds.

    This assumes loading from useFetch is a boolean.

    Also, you can use optional chaining in the jobs.map render if you are using ES2020. You can avoid writing an additional check.