https://github.com/NiGhTTraX/react-connect-state
Connect state containers to React views in a type safe and simple way
https://github.com/NiGhTTraX/react-connect-state
react state store time-travel typescript
Last synced: 5 months ago
JSON representation
Connect state containers to React views in a type safe and simple way
- Host: GitHub
- URL: https://github.com/NiGhTTraX/react-connect-state
- Owner: NiGhTTraX
- License: mit
- Created: 2019-01-06T20:59:23.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2020-08-22T12:49:49.000Z (about 5 years ago)
- Last Synced: 2024-10-31T01:34:54.426Z (11 months ago)
- Topics: react, state, store, time-travel, typescript
- Language: TypeScript
- Homepage:
- Size: 1.01 MB
- Stars: 5
- Watchers: 3
- Forks: 0
- Open Issues: 9
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
> Simple, type safe and time travelling state management for React
[](https://travis-ci.com/NiGhTTraX/react-connect-state)
[](https://codecov.io/gh/NiGhTTraX/react-connect-state) ----
## Usage
```typescript jsx
import connectToState, { StateContainer } from 'react-connect-state';
import React from 'react';
import ReactDOM from 'react-dom';interface CounterState {
count: number;
}class CounterContainer extends StateContainer {
state = {
count: 0
};increment() {
this.setState({ count: this.state.count + 1 });
}
}interface CounterViewProps {
counter: CounterContainer;
}const CounterView = ({ counter }: CounterViewProps) =>
;
{counter.state.count}
counter.increment()}>+const ConnectedCounterView = connectToState(
CounterView,
{ counter: new CounterContainer() }
);ReactDOM.render(
,
document.getElementById('root')
);
```### `StateContainer`
This is a very simple abstract base class that provides a private
`setState` method similar to React which will update the internal state
and notify all listeners. Unlike React though, this method is synchronous
so there's no danger in reading the current state while updating it.If your container needs some dependencies in order to work you can pass
them through the constructor.```typescript jsx
import { StateContainer } from 'react-connect-state';class MyStateContainer extends StateContainer<{ foo: number }> {
constructor(private foo: number) {
super();
this.state = { foo };
}
increment() {
this.setState({ foo: this.foo + 1 });
}
}const container = new MyStateContainer(42);
container.increment();
console.log(container.state.foo); // 43
```### `connectToState(View, { [propName]: container })`
The method takes a component and a mapping of props to state containers and connects them
together so that whenever the containers update their state the view
will be re-rendered. The returned HOC will accept the same props as
the original component, minus the props that will hold the containers.You can connect the same container to multiple views in a singleton
pattern by just passing the same reference to multiple connect calls.```typescript jsx
import connectToState, { StateContainer } from 'react-connect-state';
import React from 'react';class MyStateContainer extends StateContainer { }
const container = new MyStateContainer();const View1 = ({ foo }: { foo: StateContainer }) => null;
const View2 = ({ bar }: { foo: StateContainer }) => null;const ConnectedView1 = connectToState(View1, { foo: container });
const ConnectedView2 = connectToState(View2, { bar: container });
```You can also pass multiple containers:
```typescript jsx
import connectToState, { StateContainer } from 'react-connect-state';
import React from 'react';class MyStateContainer extends StateContainer { }
interface ViewProps {
foo: StateContainer,
bar: StateContainer,
}const View = ({ foo, bar }: ViewProps) =>
...;const ConnectedView = connectToState(View, {
foo: new MyStateContainer(),
bar: MyStateContainer()
});
```## Debugging and time travel

### `stateCommitGraph`
If you want to see how the state evolves, or who triggered a specific state
mutation, the lib exports a state container which holds the graph of all
state commits made by all the containers:```typescript jsx
import { stateCommitGraph } from 'react-connect-state';console.log(stateCommitGraph.state.branches[0]);
// [{
// id: 1,
// state: { todos: [], typingTodo: 'b' },
// checkout,
// instance
// }]
```### `StateCommit`
Each `setState` call in a container will create a new commit in the state commit graph. Each commit has a `checkout` method which you can use to travel back in time. Checking out a commit will reset every container's state to the state they held at that moment in time.
### Branches
After a checkout, any new state commits will create a new branch. This way no commits are overridden and you can easily go back and forth between different paths of your state flow.
### `CommitGraphDebug`
Since the commit graph is a state container you can easily connect it to
a view to monitor your app's state in real time. The lib exports a view
that is already connected and renders the commit graph in a git tree
fashion and allows you to inspect the commits and perform checkouts.```typescript jsx
import { CommitGraphDebug } from 'react-connect-state';
import React from 'react';
import ReactDOM from 'react-dom';ReactDOM.render(, document.getElementById('log'));
```## Motivation
Turn this
```typescript jsx
import React, { Component } from 'react';interface ViewState {
foo: number
}class View extends Component<{}, ViewState> {
state = { foo: 1 };
render() {
return;
Foo is {this.state.foo}
}
componentDidMount() {
setInterval(() => this.setState(
(prevState) => ({ foo: prevState.foo + 1 })
), 1000);
}
}
```into this
```typescript jsx
import connectToState, { StateContainer } from 'react-connect-state';
import React from 'react';interface FooState {
foo: number;
}class FooContainer extends StateContainer {
state = { foo: 1 };
constructor() {
super();
setInterval(() => {
this.setState({ foo: this.state.foo + 1 });
}, 1000);
}
}interface ViewProps {
foo: StateContainer
}const View = (props: ViewProps) =>
;
Foo is {props.foo.state.foo}const ConnectedView = connectToState(View, { foo: new FooContainer() });
```Decoupling state from your React views has some advantages. First of all,
you can test the state logic and the view logic separately. Secondly,
state will become easier to share between components because it will
set at a higher level from where it can be passed to multiple components.
Lastly, components can become more reusable by accepting a more generic
type of state. This becomes evident if you have components that are
coupled to APIs - by removing that state and creating a prop interface
for it, you can open up the component to receiving similar responses
from other APIs as well.## Guiding principles
### Type safety
This lib is written in TypeScript and it makes sure that when you connect
a view to a state container the view will have a prop interface accepting
that type of container.
### Dependency Injection
Pulling away the state from the views and connecting them higher up
in the app can lead to loosely coupled components. Views can become more
reusable since their state and actions can be expressed through props
and callbacks. The state containers are simple classes with a very
minimal interface that can be implemented with or without this lib or
with other libs.```typescript jsx
import connectToState, { StateContainer } from 'react-connect-state';
import React from 'react';interface DropdownState {
items: { id: number; name: string; }[];
}interface DropdownContainer extends StateContainer {
delete: (id: number) => void;
}interface DropdownProps {
items: DropdownContainer;
}const Dropdown = ({ items }: DropdownProps) =>
{items.state.items.map(item =>
{item.name}
Delete
)}
;// We're using the same Dropdown component and binding it to different
// state containers.
const UserDropdown = connectToState(Dropdown, { items: new UsersContainer() });
const ArticlesDropdown = connectToState(Dropdown, { items: new ArticlesContainer() });
```### Easy testing
Separating state from views enables testing them separately in isolation.
Taking the first example from above, the tests might look something
like this:```typescript jsx
import { describe, it } from 'mocha';
import { spy } from 'sinon';
import { expect } from 'chai';
import { render } from 'some-testing-framework';
import React from 'react';
import { CounterContainer, CounterView } from '../src';describe('CounterContainer', () => {
it('should start at zero', () => {
expect(new CounterContainer().state.count).to.equal(0);
});
it('should increment', () => {
const counter = new CounterContainer();
counter.increment();
expect(counter.state.count).to.equal(1);
});
});describe('CounterView', () => {
// You can use simple objects as containers.
const counterMock = {
state: { count: 23 },
increment: spy()
};
it('should display the counter', () => {
const component = render();
expect(component.text()).to.include('23');
});
it('should call to increment', () => {
const component = render();
component.click('button');
expect(counterMock.increment).to.have.been.calledOnce;
});
});
```## More examples
### Exporting a connected component
You can of course connect a view to a container when exporting it from
a module.```typescript jsx
import connectToState from 'react-connect-state';
import CounterContainer from './counter-container';interface CounterViewProps {
counter: CounterContainer
}const CounterView = ({ counter }: CounterViewProps) => null;
export default connectToState(CounterView, { counter: new CounterContainer() });
```This pattern is perfectly valid, though it couples the view to the
state container so it can't be used without it. This increases "out of
the box readiness" at the expense of loose coupling.### Connecting a component inline
```typescript jsx
import connectToState from 'react-connect-state';
import container from './container';
import CounterView from './view';
import React from 'react';// Connect the view once, outside your render method.
const ConnectedCounterView = connectToState(CounterView, { foo: container });// And now use it in your exported component.
export default () =>;
```This is the same as exporting a connected component although it happens
higher up the call stack - the `CounterView` component is reusable and
can be connected to any container and the component we're exporting
binds it to a particular container, effectively binding itself to that
container.### Expressing dependencies between containers
You can subscribe to containers via their `subscribe` method so there's
nothing from stopping a container listening to another container: just
pass their instances in the constructor and subscribe to them there.```typescript jsx
import connectToState, { StateContainer } from 'react-connect-state';
import React from 'react';
import ReactDOM from 'react-dom';interface ToggleState {
toggled: number;
}class Toggle extends StateContainer {
state = { toggled: false };
toggle = () => {
this.setState({ toggled: !this.state.toggled });
}
}interface ToggleCountState {
on: number;
off: number;
}const ToggleView = ({ toggle }: { toggle: StateContainer }) =>
;
{toggle.state.toggled ? 'I am on' : 'I am off'}
Toggle me!class ToggleCount extends StateContainer {
state = { on: 0, off: 0 };
constructor(toggle: StateContainer) {
super();
toggle.subscribe(this.onToggle);
}
onToggle = (toggleState: ToggleCountState) => {
if (toggleState.toggled) {
this.setState({ on: this.state.on + 1 });
} else {
this.setState({ off: this.state.off + 1 });
}
}
}const ToggleCountView = ({ toggleCount }: { toggleCount: StateContainer }) =>
;
Number of times toggled on: {toggleCount.state.on}
Number of times toggled off: {toggleCount.state.off}
const toggle = new Toggle();
const toggleCount = new ToggleCount(toggle);const ConnectedToggle = connectToState(ToggleView, { toggle: toggle });
const ConnectedToggleCount = connectToState(ToggleCountView, { toggleCount: toggleCount });ReactDOM.render(
, document.getElementById('root'));
```