Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cheatsheet request: unstated #481

Open
vincentaudebert opened this issue Apr 5, 2018 · 0 comments
Open

Cheatsheet request: unstated #481

vincentaudebert opened this issue Apr 5, 2018 · 0 comments

Comments

@vincentaudebert
Copy link

unstated is a cool state manager based on the new Context API with a polyfill for older React versions.
More info here: https://github.com/jamiebuilds/unstated

Container:

import { Container } from 'unstated';

type CounterState = {
  count: number
};

class CounterContainer extends Container<CounterState> {
  state = {
    count: 0
  };

  increment() {
    this.setState({ count: this.state.count + 1 });
  }

  decrement() {
    this.setState({ count: this.state.count - 1 });
  }
}

Subscribed Component:

import { Subscribe } from 'unstated';
const Counter = () => {
  return (
    <Subscribe to={[CounterContainer]}>
      {counter => (
        <div>
          <button onClick={() => counter.decrement()}>-</button>
          <span>{counter.state.count}</span>
          <button onClick={() => counter.increment()}>+</button>
        </div>
      )}
    </Subscribe>
  );
}

Provider Component:

import { Provider } from 'unstated';
const ProviderComponent = () => {
  return (
    <Provider>
      <Counter />
    </Provider>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants