shallow-equal-explain
TypeScript icon, indicating that this package has built-in type declarations

0.0.4 • Public • Published

shallow-equal-explain

This package provides a shallowEqualExplain function which is a copy of the shallowEqual function used by React's PureComponent, but instead of returning a boolean, it returns an object explaining the difference.

This is useful when you're trying to debug PureComponents, or any use of shallowEqual for that matter.

shallowEqualExplain has type:

function shallowEqualExplain<A, B>(objA: A, objB: B): Explanation;

Explanation is defined as:

type Explanation = 
    | ObjectSame
    | ObjectDifferent
    | PropertiesSame
    | PropertiesDifferent;

ObjectDifferent and PropertiesDifferent provide further detail through their explanation properties, which have types ObjectDifferentExplanation and PropertiesExplanation respectively:

type ObjectDifferentExplanation = NotObjectOrNull | NonMatchingKeys;
 
type PropertyExplanation = Same | Different;
type PropertiesExplanation<Keys extends string> = {
    [key in keys]: Same | Different
};

Example

t.deepEqual(
    shallowEqualExplain({ a: 1, b: 2, c: {} }, { a: 1, b: 2, c: {} }),
    Explanation.PropertiesDifferent({
        explanation: {
            a: PropertyExplanation.Same({}),
            b: PropertyExplanation.Same({}),
            c: PropertyExplanation.Different({}),
        },
    }),
);

Installation

yarn add shallow-equal-explain

Usage

import { shallowEqualExplain } from 'shallow-equal-explain';
 
shallowEqualExplain({ a: 1, b: 2, c: {} }, { a: 1, b: 2, c: {} });

With React:

class MyComponent extends React.PureComponent {
    componentDidUpdate(prevProps) {
        const currentProps = this.props;
        const shallowEqualExplanation = shallowEqualExplain(
            prevProps,
            currentProps,
        );
 
        console.log({ prevProps, currentProps, shallowEqualExplanation });
    }
 
    render() {
        return <div>My component</div>;
    }
}

See the tests for a full set of examples.

Development

yarn
npm run start

Dependencies (2)

Dev Dependencies (7)

Package Sidebar

Install

npm i shallow-equal-explain

Weekly Downloads

1,085

Version

0.0.4

License

none

Last publish

Collaborators

  • oliverjash