Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Robust way to handle app errors inside mapStateToProps?

I'm looking for advice on the most robust and reliable way to handle errors within mapStateToProps, and if it's even advisable to attempt this at this level within a React+Redux app.

For example, if I use react-redux's connect with a component and a mapStateToProps:

function mapStateToProps(state, ownProps) {
    throw Error('Some unfortunate error.');
    return {
        // some data
    }
}

I want to catch this error and maybe display an error component in the place of the rendering component. I will not make any attempt to recover - just pick up and move on.

At the moment I've noticed that this stalls React completely, and the page will probably need to be reloaded: Uncaught TypeError: Cannot read property 'getHostNode' of null

like image 612
Will Morgan Avatar asked Oct 30 '22 16:10

Will Morgan


1 Answers

I would handle the exception as regular data since connect would still expect some props to pass them to your component. I'd do something like this:

function mapStateToProps(state, ownProps) {
 try {
   // code
   return {
       // some data
   }
 } catch (e){
   return {
       error: e
   }
 }
}

And then have the component look for props.error and display an error message.

like image 135
Rami Enbashi Avatar answered Nov 09 '22 16:11

Rami Enbashi