React + Alt.js dispatch in the middle of dispatch problem
Click on 'LOGIN' button fires off a LOGIN action, which triggers an async call that eventually fires LOGIN_RESPONSE. This causes Content component to be mounted which attempts to fire FETCH but it is still in the dispatch of LOGIN_SUCCESS.
by ians
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://fb.me/react-with-addons-0.14.6.js"></script>
<script src="https://fb.me/react-dom-0.14.6.js"></script>
<script src="https://rawgit.com/goatslacker/alt/master/dist/alt.min.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="container"></div>
JavaScript 1.7
var alt = new Alt();
var MyActions = alt.generateActions('login', 'loginResponse', 'fetchData');
var MySource = {
login() {
return {
remote(state) {
return new Promise((resolve, reject) => {
setTimeout(() => { resolve('Mr. Fiddle'); }, 500);
});
},
loading: MyActions.login,
success: MyActions.loginResponse,
error: MyActions.loginResponse
}
}
};
class MyStoreDef {
constructor() {
this.user = null;
this.data = null;
this.bindListeners({
handleLogin: MyActions.LOGIN,
handleLoginResponse: MyActions.LOGIN_RESPONSE,
handleFetchData: MyActions.FETCH_DATA
});
this.registerAsync(MySource);
}
handleLogin() {
console.log('login');
this.user = null;
}
handleLoginResponse(name) {
console.log('login response');
this.user = name;
}
handleFetchData() {
console.log('fetch data');
this.data = 'some data';
}
}
var MyStore = alt.createStore(MyStoreDef, 'MyStore');
class Content extends React.Component {
componentDidMount() {
//setTimeout(() => {
MyActions.fetchData();
//}, 0);
}
render() {
return <div>Some Content</div>;
}
}
class Wrapper extends React.Component {
constructor() {
super();
this.state = MyStore.getState();
this.onChange = this.onChange.bind(this)
}
componentDidMount() {
MyStore.listen(this.onChange);
}
onChange(state) {
this.setState(state);
}
render() {
if (!this.state.user) {
return (
<div>
<button onClick={MyStore.login}>LOGIN</button>
</div>
);
} else {
return (
<div>
Welcome, {this.state.user} - data={this.state.data}
<Content/>
</div>
);
}
}
}
ReactDOM.render(
<Wrapper/>,
document.getElementById('container')
);