Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Does anyone have an idea on why this useFetch hook is not fetching anything? Chrome Devtools says the beerId is fine, it is passed in, it is read by the inner async function, but the fetch is not sent at all. Network tab shows no API call. Therefore, the output is an empty object, not good. What am I missing? The API is otherwise fine, my other calls return responses alright. Cheers.

export const useFetch = (beerId, initialValue) => {
    const [isLoading, setLoading] = useState(false);
    const [data, setData] = useState(initialValue); 
    useEffect(() => {
        async function fetchBeerById() {
            try {
                setLoading(true)
                const res = await fetch(`https://api.punkapi.com/v2/beers/${beerId}`);
                const beer = await res.json();
                setData(beer)
            } catch (err) {
                console.log(err)
            } finally {
                setLoading(false)
            }
        }
        fetchBeerById()
    },[beerId])
    return { data, isLoading}
}  

This is how I use it in the app:

const BeerDetails = () => {
  // get id from URL
  const params = useParams();
  const { beerId } = params;
  debugger
  // fetch that beer, apply local price
  const { data } = useFetch(beerId, {})
  const beer = usePriceBeer(data)
  
  // get the selected data from beer
  const selectBeerData = getSelectedBeerDetails(beer)
  const { name, image_url, abv, ibu, price, tagline, description } = 
  selectBeerData;
 
  return (...render jsx using above vars)
  
}

And here is what I see in the DevTools. For some reason, the fetch command is a dud. If I hover over res nothing pops up, the API call is not even fired. In fact, the whole useEffect block is just skipped, not even isLoading is set back to false.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
317 views
Welcome To Ask or Share your Answers For Others

1 Answer

The problem could be data is null on the initial load and you get an empty object.

I tried to create a prototype for it and just return null if there is no data. So only return data when it exits with isLoading.

https://codesandbox.io/s/recursing-banzai-b2y0c

make sure to check lines 26 and 40


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...