vasilis 123
vasilis 123

Reputation: 675

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>  
  );
  
} 

Upvotes: 0

Views: 1972

Answers (2)

Zia ur Rehman
Zia ur Rehman

Reputation: 565

Here is a solution you should try something like this.

export default function JobList() {
  
  const [loading, setLoading] = useState(true);
  const request = useFetch('https://example.com')

  request.post('/todos', {
    any: 'data'
  }).then(response => {
      settimeout(() => {
          setLoading(false)
      }, 1000 ) // here you can set delay
  }).catch(error => {
      // error handing here...
  })

  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>  
  );
  
}

Upvotes: 1

Tom Bombadil
Tom Bombadil

Reputation: 3975

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.

Upvotes: 1

Related Questions