all files / src/ wrap.js

100% Statements 22/22
100% Branches 8/8
100% Functions 4/4
100% Lines 22/22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46     27×       27× 216×   216× 64×     152× 123× 123×     13×   13×         10×           27×   27×      
const React = require('react');
const lifeCycleMethods = require('./lifeCycleMethods');
const debug = require('debug')('react-safe-component');
 
const wrap = (Component) => {
 
    if (!Component.prototype.renderSafeComponentError) {
        Component.prototype.renderSafeComponentError = function () {
            return 'Oops... an error has occured';
        };
    }
 
    const wrapMethod = (methodName) => {
        const originalMethod = Component.prototype[methodName];
 
        if (!originalMethod) {
            return;
        }
 
        Component.prototype[methodName] = function () {
            try {
                return originalMethod.apply(this, arguments);
 
            } catch (e) {
                debug(e);
 
                if (methodName === 'render') {
                    return React.createElement('div', {
                        className: 'react__safecomponent-error'
                    }, Component.prototype.renderSafeComponentError());
                }
 
                if (methodName === 'shouldComponentUpdate') {
                    return false;
                }
            }
        };
    };
 
    lifeCycleMethods.forEach(wrapMethod);
 
    return Component;
};
 
module.exports = wrap;