Home > Blockchain >  try catch or async awaiit in useeffect for jest
try catch or async awaiit in useeffect for jest

Time:02-12

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:>2017-01-10&sort=stars&order=desc")
    .then((res) => res.json())
      .then((data) => {
        setData(data)
        setLoading(false)
      })
  }, [500]);

CodePudding user response:

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:>2017-01- 
         10&sort=stars&order=desc")
    const json = await data.json();
    if(json){
        setData(json)
        setLoading(false)
      } 
     }catch(err=>{
             console.log(err)
      })
    
   }, [500]);

CodePudding user response:

 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:>2017-01-10&sort=stars&order=desc")
        const data = await res.json()
        setData(data)
        setLoading(false)
     }catch(err=>{
        console.log(err)
      })
    
   }, [500]);
  • Related