Search code examples
javascriptreactjsreact-hooksasync-awaittry-catch

try...catch needed in async call inside useEffect?


I'm trying to do some async stuff in a useEffect hook. So first I define the async function and second I'm calling that function. I am not quite sure how to handle errors correctly. Is the try...catch part also needed as the .catch of the function call? Isn't it the same?

useEffect(() => {
  const fetchData = async () => {
    try {
      const token = await AsyncStorage.getItem('auth.token')
      // do something
    } catch (e) {
      console.error(e)
    }
  }

  fetchData().catch(console.error)
}, [])

Solution

  • You have two options to handle asynchronous operations in JavaScript, you can use async await or .then() & .catch(). Here is an example of both:

    useEffect(() => {
      const fetchData = async () => {
        try {
          const token = await AsyncStorage.getItem('auth.token')
          // do something
        } catch (e) {
          console.error(e)
        }
      }
    
      fetchData()
    }, [])

    useEffect(() => {
      const fetchData = () => {
        AsyncStorage.getItem('auth.token')
          .then(token => console.log(token))
          .catch(err => console.error(err))
      }
      fetchData()
    }, [])