Skip to content

Instantly share code, notes, and snippets.

@prabirshrestha
Created July 21, 2015 17:10
Show Gist options
  • Save prabirshrestha/6f928884ec193aaefb6a to your computer and use it in GitHub Desktop.
Save prabirshrestha/6f928884ec193aaefb6a to your computer and use it in GitHub Desktop.
sample flux
export function increment() {
return {
type: 'INCREMENT'
};
}
function decrement() {
return {
type: 'DECREMENT'
};
}
// async actions
export function incrementAsync() {
return (dispatch, select) => {
var incrementStore = select('counter');
console.log(incrementStore.getState());
setTimeout(()=> dispatch(increment()), 2000);
};
}
import React from 'react';
import { Dispatcher } from './dispatcher';
import { counterReducer } from './reducer';
const COUNTER_STORE = 'counter';
var dispatcher = new Dispatcher();
dispatcher.register(COUNTER_STORE, counterReducer);
export class App extends React.Component {
constructor(props) {
super(props);
this.counterStore = dispatcher.select(COUNTER_STORE);
this.state = { counter: this.counterStore.getState() };
}
handleIncrement(e) {
e.preventDefault();
dispatcher.dispatch(increment());
}
handleDecrement(e) {
e.preventDefault();
dispatcher.dispatch(decrement());
}
handleIncrementAsync(e) {
e.preventDefault();
dispatcher.dispatch(incrementAsync());
}
componentDidMount() {
this.unsubscribe = this.counterStore.subscribe(state => {
this.setState({ counter: state });
});
}
componentWillunMount() {
this.unsubscribe();
}
shouldComponentUpdate(_, nextState) {
return nextState.counter !== this.state.counter;
}
render() {
return <div>
<button onClick={this.handleIncrement}>Increment</button>
<button onClick={this.handleDecrement}>Decrement</button>
<button onClick={this.handleIncrementAsync}>Increment Async</button>
<label>{this.state.counter} count</label>
</div>;
}
}
export function counterReducer(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment