Skip to content

Instantly share code, notes, and snippets.

@neftaly
Created February 24, 2020 07:17
Show Gist options
  • Save neftaly/5ea0c8a73835ebc68077f9459890ac46 to your computer and use it in GitHub Desktop.
Save neftaly/5ea0c8a73835ebc68077f9459890ac46 to your computer and use it in GitHub Desktop.
meiosis + flyd + immutable
import React, { memo } from 'react';
import { render } from 'react-dom';
import { stream, scan } from 'flyd';
import { fromJS } from 'immutable';
const Box = memo(props => {
const { id, value } = props;
// Show re-renders by changing bg color
const color = Math.round(Math.random() * 1000);
return (
<input
value={value}
onChange={actions.change(id)}
style={{ border: '10px solid #' + color }}
/>
);
});
const Main = memo(props => {
const { actions, state } = props;
return (
<div>
<Box
id='text1'
actions={actions}
value={state.get('text2')}
/>
<Box
id='text2'
actions={actions}
value={state.get('text1')}
/>
</div>
);
});
const initial = fromJS({
deeply: {
nested: {
text1: 'hello',
text2: 'world'
}
}
});
const Actions = update => ({
change: id => e => update(
i => i.setIn(
['deeply', 'nested', id],
e.target.value
)
)
});
const update = stream();
const actions = Actions(update);
const states = scan(
(state, patch) => patch(state),
initial,
update
);
class Root extends React.Component {
constructor (props) {
super(props);
this.state = {
meiosis: props.states() // Get the latest (first) state
};
}
componentDidMount () {
this.props.states.map(
meiosis => this.setState({ meiosis })
);
}
render () {
return (
<Main actions={this.props.actions} state={this.state.meiosis} />
);
}
}
render(
<Root states={states} actions={actions} />,
document.getElementById('root')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment