Skip to content

Instantly share code, notes, and snippets.

@Palatnyi
Last active September 26, 2019 16:29
Show Gist options
  • Save Palatnyi/9a6cb87224d99a86391add2f06e6a4b1 to your computer and use it in GitHub Desktop.
Save Palatnyi/9a6cb87224d99a86391add2f06e6a4b1 to your computer and use it in GitHub Desktop.
import React, {Component, PureComponent, createContext} from 'react';
const Context = createContext();
class User {
constructor(getState, rootUpdater) {
this._getState = getState;
this._rootUpdater = rootUpdater;
this.name = '';
this.surname = '';
}
_setValue = (value = {}) => {
this._rootUpdater({
user: {
setName: this.setName,
setSurname: this.setSurname,
...this._getState().user,
...value
}
});
};
setName = (name = '') => {
this._setValue({name});
}
setSurname = (surname = '') => {
this._setValue({surname});
}
}
class Store extends Component {
constructor(props) {
super(props);
this.rootUpdater = (data = {}) => {
this.setState({
...this.state,
...data
})
};
this.getState = () => {
return this.state;
};
const user = new User(this.getState, this.rootUpdater);
this.state = {user};
}
render() {
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
);
}
}
function Layout() {
return (
<div>
<Title />
<Input />
</div>
);
}
class Title extends PureComponent {
static contextType = Context;
render() {
return (
<div>
<h3>
name {this.context.user.name}
</h3>
<h3>
surname {this.context.user.surname}
</h3>
</div>
);
}
}
class Input extends PureComponent {
static contextType = Context;
constructor(props) {
super(props);
this.nameInput = React.createRef();
this.surnameInput = React.createRef();
}
setName = (e) => {
this.context.user.setName(e.target.value);
}
setSurname = (e) => {
this.context.user.setSurname(e.target.value);
}
render() {
return (
<div>
<div>
<p>change name </p>
<input ref={this.nameInput} onChange={this.setName} />
</div>
<div>
<p>change name </p>
<input ref={this.surnameInput} onChange={this.setSurname} />
</div>
</div>
);
}
}
export function App() {
return (
<Store>
<Layout />
</Store>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment