React JS: Debugging

1st Aug 18
puppy

In this article I will be going through the ways you can handle errors.  

You can create components that handle errors.  This is called error boundary.   Within a folder called ErrorBoundary, you create a classed based component.  Add a method called componentDidCatch, this method will receive the error and any additional information from React.  The method will be executed when an error is thrown within a component that is wrapped with the error boundary.  The the render method we either return the error message or the component that is wrapped within the Error Boundary (this.props.children).

 

// ErrorBoundary.php

import React, { Component } from 'react';

class ErrorBoundary extends Component{
    state = {
        hasError: false,
        errorMessage: ''
    }
    
    componentDidCatch = (error, info) => {
        this.setState({hasError: true, errorMessage: error});
    }

    render(){
        if(this.state.hasError){
            return <h1>{this.state.errorMessage}</h1>;
        }else{
            this.props.children;
        }

       
    }
}

...
//within the App.js
      
return <ErrorBoundary><Person 
                  click={()=>this.deletePersonHandler(index)}
                  name={person.name} 
                  age={person.age}
                  key = {person.id}
                  changed = {(event) => this.nameChangedHandler(event, person.id)}/>
                  </ErrorBoundary> 
...

 

I have recently completed my apprenticeship.  I am currently building the API to a React JS site using Firebase.