Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda