0

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

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.