Why shouldn't I use catch() to handle errors in React useEffect API calls?

C. Ball

On this page of the React docs:

https://reactjs.org/docs/faq-ajax.html

A code comment says...

Note: it's important to handle errors here instead of a catch() block so that we don't swallow exceptions from actual bugs in components.

...about handling errors in the second argument to the second .then after fetch. The complete snippet from the docs is:

  useEffect(() => {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, [])

It doesn't elaborate on this advice, and I've seen many examples of working React code using catch to handle errors from API calls. I've tried Googling but can't find any clarification.

Could someone please give me a more detailed explanation as to why I shouldn't use catch to deal with errors that arise when making a fetch API call in a useEffect hook?

Or are there some situations when it's ok to do so, but others when it's not?

What is meant by "swallow exceptions [...] in components" ?

Does this rule/guideline apply to all of React, or just to API calls?

Or just to the useEffect hook or componentDidMount lifecycle method?

Martin

It is a copy-and-paste error of the example's author. The first example uses the component state of a class based component: this.setState() causes a synchronous re-render (or at least this was the case with react v15.0 in 2016, not sure if it holds true today). Therefore the warning comment and the use of the second arg to .then(onResolve, onReject) is justified. The second example uses the useState hook of a function component: setState causes no synchronous re-render only an asynchronous re-render. Therefore the warning comment and the use of the second arg to .then(onResolve, onReject) is not justified.

To illustrate this: with useState hooks you can call multiple updaters and they all will only take effect in one re-render.

const [a, setA] = useState();
const [b, setB] = useState();
const [c, setC] = useState();

const updateState = () => {
  setA('foo');
  setB('bar');
  setC('buz');
  // will only cause one single re-render
}

and therefore its perfectly fine to use catch

useEffect(() => {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
        }
      )
      .catch(
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, [])

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Why I shouldn't use toJS() in React Redux? (mapStateToProps)

React Native UseEffect API CALLS

Why shouldn't I use immutable POJOs instead of JavaBeans?

Why shouldn't I use max value for max_connections

Why shouldn't I use mysql_* functions in PHP?

Why shouldn't I use System.out.println() in android

C# Why shouldn't I ever use coroutines?

Why I Shouldn't use Nothing in Place of Unit

Why shouldn't I catch Undefined Instruction exception instead of using CPUID?

Where I handle API calls in react-native and redux

Why am I receiving intermittent duplicate update errors on a MERGE statement, where it shouldn't be possible?

Why java applets/javafx aren't widely used? (why I shouldn't use them for RIA)

Why I can't use dispatch a thunk inside useEffect?

If I shouldn't use functions within my Angular template, why does it seem to be okay to use formControl .get()?

my Button in react dosen't work - I use useState and useEffect

Why shouldn't I mix tabs and spaces?

Why shouldn't I turn off UAC?

Why shouldn't I read files in a SourceGenerator?

Why shouldn't i get response when i use http services

Why shouldn't I use ioremap on system memory for ARMv6+?

Why shouldn’t I use my 4G mobile connection for business Internet?

Why shouldn't I use apt-get install --qq without a no-action modifier?

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

If my database column has a lot of null values, why shouldn't I use an index on it?

Why shouldn't I use this porcelain Git command to tell if my repo has any changes?

Why I shouldn't use "Repeatable Read" with locking reading (select..for update)"?

Why shouldn't I use mysql_* functions in PHP?

Use Try-Catch to handle seen errors, is it bad?

How to correctly catch and handle errors in Http get request to Facebook api

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive