React Observer Mixin
A React.js Mixin with ES5 and ES6-compatible semantics which provides managed event listeners that respect component lifecycles, as well as state setters which are compatible with React invariants and are suitable for use in one-time event handlers.
This module has no runtime dependencies and weighs in at ~1.3kB minified.
Why does this exist?
Asynchronous callbacks which operate on a component's state will violate React's invariants if the component is not mounted when the callback is executed. This utility offers a mixin for React Component providing the following functionality:
-
listenTo: Managed event listening respecting component lifecycles. Listeners are automatically detached when the component is un-mounted.
-
setStateIfMounted: Conditional state setting which helps to avoid a violation of React's invariants when you know that you can safely drop the result of an asynchronous request.
ES6 Example
; Component { superprops; // Attach mixin methods and spies necessary to support them. ; // The event handler automatically detaches when this component // is un-mounted. this; // Other forms of async callbacks ; }
ES5 Example
var ObserverMixin = Mixin; var MyComponent = React;
Definitions
Term | Definition |
---|---|
Mixin | Refers to this module's Mixin returned by the build function |
Observable | Object providing on or addEventListener methods |
API
Module
(Mixin) module.build
Generate a Mixin which can be provided to the list of mixins for a React component.
See above for example usage.
module.mixin(React.Component)
Attach Mixin methods to an React.Component built in an ES6 fashion.
Provided Mixin Methods
this.listenTo(Observable, StringOrObject, [Function])
Attaches one or more managed listeners to an observable object. The event listeners will be detached when the component is un-mounted, and re-attached if/when the component is mounted again.
Example:
// ... { this; // For ease of use, multiple handlers may be attached by using // an object as the second parameter. this; }
this.setStateIfMounted(Object)
Sets state if and only if the component is currently mounted. If the component is un-mounted, this call will be ignored and any given state will be silently dropped.
Contributors
Accounts with accepted PRs will be added to this list.
- Chris Carpita