Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
try catch or async awaiit in useeffect for jest

I am running my first unit tests in JEST. I installed Jest Fetch Mock but I still receive an error, "The promise rejected with reason FetchError".

I did some reading, and I guess that I need to add an async await or a try catch. Can someone help me with this?

This is the fetch I am making in useEffect.

const [data, setData] = useState(null);
  const [isLoading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true)
    
    fetch("https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc")
    .then((res) => res.json())
      .then((data) => {
        setData(data)
        setLoading(false)
      })
  }, [500]);
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

This worked better

const fetchList = async () => {

const newList = await fetch("https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc") .then((res) => res.json()) .then((data) => { setData(data) setLoading(false) }) } fetchList() }, [500]);

about 4 years ago · Juan Pablo Isaza Report

0

You Can try this ,

 const [data, setData] = useState(null);
 const [isLoading, setLoading] = useState(false);

 useEffect(async() => {
   setLoading(true)
   try{
        const data = await 
          fetch("https://api.github.com/search/repositories? 
              q=created:%3E2017-01- 
         10&sort=stars&order=desc")
    const json = await data.json();
    if(json){
        setData(json)
        setLoading(false)
      } 
     }catch (e) {
    console.error(e);
    }
    
   }, [500]);
about 4 years ago · Juan Pablo Isaza Report

0

 const [data, setData] = useState(null);
 const [isLoading, setLoading] = useState(false);

 useEffect(async() => {
   setLoading(true)
   try{
        const res = await fetch("https://api.github.com/search/repositories?q=created:%3E2017-01-10&sort=stars&order=desc")
        const data = await res.json()
        setData(data)
        setLoading(false)
     }catch(err=>{
        console.log(err)
      })
    
   }, [500]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!