I'm busy learning ReactJS with Flux and I have this interesting issue. I'm busy trying to extend the shopping cart example that egghead.io gave. https://egghead.io/lessons/react-flux-overview-and-dispatchers[^]
Current Setup: I have a .Net WebApi returning a JSON result of a list of items. This is the json result (has been shortened for brevity):
[
{
"Items":
{
"Title": "Item 1",
"Cost": 10,
"Id": 1
},
}
]
Cart Component:
/** @jsx React.DOM */
var React = require('react');
var AppStore = require('../stores/app-store.js');
var AddToCart = require('../components/app-addtocart.js');
var Catalog = React.createClass({
getInitialState: function(){
return {items: AppStore.getCatalog()};
},
render: function(){
var items = this.state.items.map(function (item){
return <tr><td>{item.title}</td><td>R{item.cost}</td><td><AddToCart item={item} /></td></tr>
});
return (
<table className="table table-hover">
{items}
</table>
)
}
});
module.exports = Catalog;
App-Store:
var AppConstants = require('../constants/app-constants.js');
var AppDispatcher = require('../dispatchers/app-dispatcher.js');
var merge = require('react/lib/merge');
var EventEmitter = require('events').EventEmitter;
var api = require('../api.js');
var request = require('superagent');
var jquery = require('jquery');
var CHANGE_EVENT = 'change';
var _cartItems = [];
var catalogItems = [];
var AppStore = merge(EventEmitter.prototype, {
emitChange: function () {
this.emit(CHANGE_EVENT);
},
addChangeListener: function (callback) { //When the component changes, do this this event and call this method (callback)
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function (callback) { //When the component changes, do this this event and call this method (callback)
this.on(CHANGE_EVENT, callback);
},
getCatalog: function () {
jquery.ajax({
url: 'http://localhost:6589/api/catalog',
contentType: 'application/json',
success: function (data) {
data.Items.map(function (item) {
catalogItems.push(item);
});
}
});
return catalogItems;
},
getCart: function () {
return _cartItems;
},
});
module.exports = AppStore;
Here is my problem: In the cart-component's getInitialState() method, when the Ajax call returns, the catalog array is being supposed to be populated. However, after checking the result returned from the AppStore.getCatalog(), the count is 0. I have no idea why this is happening as I am directly populating the array.
Things I've checked
* The scope of the variables: I even tried to create a local variable and return that.
* I have checked there is data being returned from the server
* That there aren't any JavaScript errors in the App-store
* I even removed the .map() method and manually assigned the cartItems to the json response (cartItems = data.Items)
* Spent a good half the day trying to Google answers, I've tried youtube for tutorials as well, no joy.
I'm really battling here.
Thank you Charles