Skip to content

Instantly share code, notes, and snippets.

@junkycoder
Last active November 15, 2016 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junkycoder/878c7e83835659f14465e951d29cc53a to your computer and use it in GitHub Desktop.
Save junkycoder/878c7e83835659f14465e951d29cc53a to your computer and use it in GitHub Desktop.
concept
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
/**
* Statefull application
*/
class App extends Component {
/**
* Application state
*/
state = {
viewsCount: 0,
usersClickEventInTime: [],
}
/**
* Action inicializer
*/
action(handler, payload) {
// Direct access to the state, what ever.
const state = this.state;
// Update function
const done = () => this.forceUpdate();
// Hey me, Don't lose your context.
const action = (...params) => this.action(...params);
return (event) => {
handler({ done, payload, state, event, action });
};
}
render() {
return (
<div>
<p>Page views {this.state.viewsCount}</p>
<button onClick={this.action(addView, this.state.viewsCount)}>
Add View
</button>
<input
type="text"
onChange={this.action(changeViewCount, this.state.viewsCount)}
value={this.state.viewsCount}
/>
</div>
);
}
}
// Pure action functions
function addView({ action, done, payload, state, event }) {
// Direct changes (using state object reference)
state.viewsCount++;
// Payload is current number of user view,
state.usersClickEventInTime[payload] = event; // Something like history or what.
// Stats Feature
if (payload % 10 === 0) { // ... every 10 frames
// Inside action we can fire another action
action(showStats)(); // Don't miss () on the end
}
// Next frame to propagate state changes
done();
}
function showStats({ state }) {
console.log(state.usersWiewsInTime);
// No state changes so no done() call
}
function changeViewCount({ done, state, event }) {
const value = Number(event.target.value);
if (!Number.isNaN(value)) {
state.viewsCount = value;
done();
}
}
// Render application to her container
ReactDOM.render(<App />, document.getElementById('container'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment