UNPKG

undux

Version:

Dead simple state management for React

56 lines 2.38 kB
import * as React from 'react'; import { createStore } from '..'; import { getDisplayName } from '../utils'; export function createConnectedStore(initialState, effects) { let Context = React.createContext({ __MISSING_PROVIDER__: true }); class Container extends React.Component { constructor(props) { super(props); // Create store definition from initial state let state = props.initialState || initialState; this.storeDefinition = createStore(state); // Apply effects? let fx = props.effects || effects; if (fx) { fx(this.storeDefinition); } this.state = { storeSnapshot: this.storeDefinition.getCurrentSnapshot(), }; this.subscription = this.storeDefinition.onAll().subscribe(() => this.setState({ storeSnapshot: this.storeDefinition.getCurrentSnapshot(), })); } componentWillUnmount() { this.subscription.unsubscribe(); this.storeDefinition.storeSnapshot = null; this.storeDefinition = null; } render() { return (React.createElement(Context.Provider, { value: this.state.storeSnapshot }, this.props.children)); } } let Consumer = (props) => (React.createElement(Context.Consumer, null, (store) => { if (!isInitialized(store)) { throw Error(`[Undux] Component "${props.displayName}" does not seem to be nested in an Undux <Container>. To fix this error, be sure to render the component in the <Container>...</Container> component that you got back from calling createConnectedStore().`); } return props.children(store); })); function withStore(Component) { let displayName = getDisplayName(Component); let f = (props) => (React.createElement(Consumer, { displayName: displayName }, (storeSnapshot) => (React.createElement(Component, { store: storeSnapshot, ...props })))); f.displayName = `withStore(${displayName})`; return f; } return { Container, useStore() { return React.useContext(Context); }, withStore, }; } function isInitialized(store) { return !('__MISSING_PROVIDER__' in store); } //# sourceMappingURL=createConnectedStore.js.map