1

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

h4ck3r8ug5
  • 87
  • 8
  • FYI, you have a trailing comma in your JSON, right after the `Items` object. Not all browsers deal well with this syntax error. – Phil Mar 13 '15 at 06:03
  • Also, I get the feeling you're not handling the asynchronous request properly. I haven't done any React but my guess is that the `items` property in the `getInitialState` return value is only getting the empty list **before** the request has completed. – Phil Mar 13 '15 at 06:08
  • @Elclanrs: Thank you for the link mate - it is exactly what I needed. Didn't even cross my mind that is was an asynchronous call. For a POC, I added the async:false to the ajax call and its working. I'll refactor the code to handle the async call. – h4ck3r8ug5 Mar 13 '15 at 07:15

0 Answers0