Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

103
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]);
7 months 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]);

7 months 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]);
7 months 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]);
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos