EzDevInfo.com

flux

Fluent Regular Expressions for PHP

Strategies for server-side rendering of asynchronously initialized React.js components

One of the biggest advantages of React.js is supposed to be server-side rendering. The problem is that the key function React.renderComponentToString() is synchronous which makes it impossible to load any asynchronous data as the component hierarchy is rendered on the server.

Let's say I have a universal component for commenting which I can drop pretty much anywhere on the page. It has only one property, some kind of identificator (for example id of an article bellow which the comments are placed), and everything else is handled by the component itself (loading, adding, managing comments).

I really like the Flux architecture because it makes a lot of things much easier and also it's Stores are perfect for sharing state between server and client. Once my store containing comments is initialized, I can just serialize it and send it from server to client where it is easily restored.

The question is what is the best way to populate my store. During past days I've been googling a lot and I've come across few strategies, none of which seemed really good considering how much this feature of React is being "promoted".

  1. In my opinion, the simplest way is to populate all my stores before the actual rendering begins. That means somewhere outside of the component hierarchy (hooked to my router for example). The problem with this approach is that I would have to pretty much define the page structure twice. Consider a more complex page, for example a blog page with many different components (actual blog post, comments, related posts, newest posts, twitter stream...). I would have to design the page structure using React components and then somewhere else I would have to define the process of populating each required store for this current page. That doesn't seem like a nice solution to me. Unfortunately most isomorphic tutorials are designed this way (for example this great flux-tutorial).

  2. React-async. This approach is perfect. It lets me simply define in a special function in each component how to initialize the state (doesn't matter whether synchronously or asynchronously) and these functions are called as the hierarchy is being rendered to HTML. It works in a way that a component is not rendered until the state is completely initialized. The problem is that it requires Fibers which is, as far as I understand, a Node.js extension that alters the standard JavaScript behavior. Although I really like the result, it still seems to me that instead of finding a solution we changed the rules of the game. And I think we shouldn't be forced to do that to use this core feature of React.js. I'm also not sure about the general support of this solution. Is it possible to use Fiber on standard Node.js webhostings?

  3. I was thinking a little on my own. I haven't really thought trough the implementation details but the general idea is that I would extend the components in similar way to React-async and then I would repeatedly call React.renderComponentToString() on the root component. During each pass I would collect the extending callbacks and then call them at the and of the pass to populate the stores. I would repeat this step until all stores required by current component hierarchy would be populated. There are many things to be solved and I'm especially not sure about the performance.

Did I miss something? Is there another approach/solution? Right now I'm thinking about going the react-async/fibers way but I'm not completely sure about it as explained in the second point.

Update: Related discussion on GitHub. Apparently, there is no official approach or even solution. Maybe the real question is how the React components are intended to be used. Like simple view layer (pretty much my suggestion number one) or like real independent and standalone components?


Source: (StackOverflow)

React + Flux and Server-side rendering? (Isomorphic React + Flux)

What is the general practice of setting the initial state of the app with isomorphic applications? Without Flux I would simple use something like:

var props = { }; // initial state
var html = React.renderToString(MyComponent(props);

Then render that markup via express-handlebars and display via {{{reactMarkup}}.

On the client-side to set the initial state I would do something like this:

if (typeof window !== 'undefined') {
    var props = JSON.parse(document.getElementById('props').innerHTML);
    React.render(MyComponent(props), document.getElementById('reactMarkup'));
}

So yes essentially you are setting the state twice, on server and client, however React will compare the differences and in most cases so it won't impact the performance by re-rendering.


How would this principle work when you have actions and stores in the Flux architecture? Inside my component I could do:

getInitialState: function() {
  return AppStore.getAppState();
}

But now how do I set the initial state in the AppStore from the server? If I use React.renderToString with no passed properties it will call AppStore.getAppState() which won't have anything in it because I still don't understand how would I set the state in my store on the server?

Update Feb. 5, 2015

I am still looking for a clean solution that does not involve using third-party Flux implementations like Fluxible, Fluxxor, Reflux.


Source: (StackOverflow)

Advertisements

javascript diagram editor (with xml export) [closed]

i have to do a webapp where the user designs a diagram using javascript and then can export it to an xml (the connections between the boxes). is there anything available?


Source: (StackOverflow)

Passing store state as props, or each component accessing global stores?

I am a bit confused by the statements: "Renders the whole application" and "Passing state to child components".

Example 1:

I have a todos app with a AppComponent and TodosListComponent. The AppComponent grabs the array of todos from the store and passes it as a property to the TodosListComponent.

Example 2:

I have a huge application with lots state. I have like 50 components building up my app. Do I want to pass all the state from the stores from AppComponent down through all the 50 components?

So I am wondering, what is the convention? It makes more sense to me to let individual components listen directly to the stores they care about. The advantage is that only individual components rerender, but why then the concept of "the whole application rerender on state change"?

What are the pros and cons of each? What is the common convention?


Source: (StackOverflow)

How to deal with relations in Flux?

Imagine something like Quora.

[
  {
    type: "question",
    answers: [
      {
        type: "answer",
        upvotes: [
          {
            type: "upvote"
          }
          /* more upvotes */
        ],
        comments [
          {
            type: "comment"
          }
          /* more comments */
        ]
      }
      /* more answers */
    ]
  }
  /* more questions */
]

I'd surely have something like a QuestionsStore. But for all child entities I'm unsure what to do with them. Coming from Backbone I'm thinking every answer should have a UpvotesStore and a CommentsStore and components would get their data from these Stores and subscribe to updates from them. As far as I understand Flux, "child"/relational stores are somewhat uncommon.

When every component subscribes to updates from QuestionsStore that leads to something like:

/* in CommentsComponent */
onUpdate: function() {
  this.setState({
    comments: QuestionsStore.getComments({questionId: 1, answerId: 1});
  });
}

or more extreme:

/* in CommentComponent */
onUpdate: function() {
  this.setState(QuestionsStore.getComment({questionId: 1, answerId: 1, commentId: 1}));
}

Since the relational data lives in a tree structure, every component needs to know all "parent" id's in order to be able to query their data from QuestionsStore. I find this somehow weird.

So what is the best Flux pattern to deal with relational (one-to-many) data structure?


Source: (StackOverflow)

Flux best practices: Stores dispatching actions, AJAX calls in Web API Utils?

enter image description here

I understand that this image has been the ultimate guide of most, if not all, Flux programmers. Having this flow in mind, I have a few questions:

  1. Is it correct/highly advisable to have all of my $.ajax calls inside my Web API Utils?
    • Callbacks call the action creators, passing the data in the process
  2. If I want my Store to make an AJAX call, I do have to call the Action Creator first, right? Is it fundamentally incorrect to call a function in Web API Utils directly from Store?
  3. Is there like a virtual one-sided arrow connecting from Store to Action Creators?
    • I have a lot of operations that do not go through views
  4. What are the Callbacks between Dispatcher and Store?
  5. What's the Web API here? Is this where you'd apply a RESTful API? Is there an example of this somewhere?
  6. Is it okay to have a logic involved (to know which Action to dispatch) in one of my Action Creators? Basically, this action receives the response from my AJAX call. This is a snippet:

    var TransportActions = {
        receiveProxyMessage: function (message, status, xhr) {
            switch (message) {
                case ProxyResponses.AUTHORIZED:
                    AppDispatcher.dispatch({
                        type: ActionTypes.LOGIN_SUCCESS,
                        reply: m
                    });
                    break;
                case ProxyResponses.UNAUTHORIZED:
                    AppDispatcher.dispatch({
                        type: ActionTypes.LOGIN_FAIL,
                        reply: m
                    });
                    break;
                ...
            }
        }
    }
    

I've seen a lot of different answers online, but I am still not sure how I would incorporate all of them in my application. TYIA!


Source: (StackOverflow)

Asynchronous data loading in flux stores

Say I have a TodoStore. The TodoStore is responsible for keeping my TODO items. Todo items are stored in a database.

I want to know what is the recommended way for loading all todo items into the store and how the views should interact with the store to load the TODO items on startup.

The first alternative is to create a loadTodos action that will retrieve the Todos from the database and emit a TODOS_LOADED event. Views will then call the loadTodos action and then listen to the TODOS_LOADED event and then update themselves by calling TodoStore.getTodos().

Another alternative is to not have a loadTodos action, and have a TodoStore.getTodos() that will return a promise with the existing TODO items. If the TodoStore has already loaded the TODO items, it just returns them; if not, then it will query from the database and return the retrieved items. In this case, even though the store now has loaded the TODO items, it will not emit a TODOS_LOADED event, since getTodos isn't an action.

function getTodos() {
   if (loaded)
      return Promise.resolve($todoItems);
   else
      return fetchTodoItemsFromDatabase().then(todoItems) {
         loaded = true;
         $todoItems = todoItems;
         return $todoItems;
      });
}

I'm sure many will say that that breaks the Flux architecture because the getTodos function is changing the store state, and store state should only be changed though actions sent in from the dispatcher.

However, if you consider that state for the TodoStore is the existing TODO items in the database, then getTodos isn't really changing any state. The TODO items are exactly the same, hence no view need to be updated or notified. The only thing is that now the store has already retrieved the data, so it is now cached in the store. From the View's perspective, it shouldn't really care about how the Store is implemented. It shouldn't really care if the store still needs to retrieve data from the database or not. All views care about is that they can use the Store to get the TODO items and that the Store will notify them when new TODO items are created, deleted, or changed.

Hence, in this scenario, views should just call TodoStore.getTodos() to render themselves on load, and register an event handler on TODO_CHANGE to be notified when they need to update themselves due to a addition, deletion, or change.

What do you think about these two solutions. Are they any other solutions?


Source: (StackOverflow)

Proper way to initialize data [duplicate]

This question already has an answer here:

What is the proper way to initialize data (asynchronously) with RefluxJS? Is there something similar to AngularJS' resolves, or the Flux implementation has nothing to do with this (The router should be handling this reponsibility)?


Source: (StackOverflow)

React Flux implement dispatch chain

i'm trying to use React with Flux architecture and stumbled on one restriction which i can't handle. Problem is as following:

  1. There's a store which listens to an event. Event has object id. We need to fetch object if needed and make it selected.
  2. If store doesn't have object with this id - it's queried. In callback we dispatch another event to store which is responsible for selection.
  3. If store has object - i'd like to dispatch selection event, but i can't because dispatch is in progress.

Best solution i came up with so far is wrapping inner dispatch in setTimeout(f, 0), but it looks scary.

Actually the problem is quite general - how should i organize dispatch chain without dispatch nesting (without violating current Flux restrictions) if each new dispatch is based on previous dispatch handling result.

Does anybody have any good approaches to solve such problems?

var selectItem(item) {
    AppDispatcher.dispatch({
        actionType: AppConstants.ITEM_SELECT,
        item: item
    });
}

// Item must be requested and selected.
// If it's in store - select it.
// Otherwise fetch and then select it.
SomeStore.dispatchToken = AppDispatcher.register((action) => {
    switch(action.actionType) {
        case AppConstants.ITEM_REQUESTED:
            var item = SomeStore.getItem(action.itemId);
            if (item) {
                // Won't work because can't dispatch in the middle of dispatch
                selectItem(item);
            } else {
                // Will work
                $.getJSON(`some/${action.itemId}`, (item) => selectItem(item));
            }
    }
};

Source: (StackOverflow)

Reflux trigger won't work without a delay in init

I use Reflux, and normally I'm triggering after I made an ajax call, and it works well. For testing purposes I didn't need ajax call and I noticed that trigger won't work unless I give a min 5ms timeout. Here are working and not working example.

Not working example:

window.threadStore = Reflux.createStore
  init: ->
    @state = @getInitialState()
    @fetchThreads()
  getInitialState: ->
    loaded: false
    threads: []
  fetchThreads: ->
    # ajax call for not Testing, and just trigger for Testing
    @state.threads = FakeData.threads(20)
    @state.loaded = true
    @trigger(@state) # This will NOT work!

This will work:

window.threadStore = Reflux.createStore
  init: ->
    @state = @getInitialState()
    @fetchThreads()
  getInitialState: ->
    loaded: false
    threads: []
  fetchThreads: ->
    # ajax call for not Testing, and just trigger for Testing
    @state.threads = FakeData.threads(20)
    @state.loaded = true
    setTimeout( =>
      @trigger(@state) # This WILL work!
    , 500)

Can you explain why doesn't it work without a delay and should it? Is it a bug or something I don't understand.


Source: (StackOverflow)

Does Jest AutoMocking work when testing React components?

My limited number of tests seem to suggest that the answer is no. I'm writing a unit test for a parent level React component (aka a controller view) that has a dependency on a store. However, Jest is not providing an auto-mock for the store, as the documentation suggests it should, and is instead calling the real implementation.

Is this a bug or by design? If the latter, is the takeaway that unit testing react components is not desirable?

Edit 1

Automocking works just fine when testing a CommonJs module; it's just not working for react components.


Source: (StackOverflow)

Do I need Flux Store for this purpose?

Let's say I have a simple form component for posting a tweet. Why would I want to create a store to keep my form state, instead of just declaring the state in getInitialState() of my form component ? After the user has typed in the form and presses submit, then only we update the state and call backend api? Why would I go through trouble of setting up action and listeners? Thanks for looking at this!


Source: (StackOverflow)

Flux Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch

My code https://gist.github.com/ButuzGOL/707d1605f63eef55e4af

So when I get sign-in success callback I want to make redirect,
redirect works through dispatcher too.

And I am getting Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.

Is there any hack to call action in the middle ?


Source: (StackOverflow)

How do I handle nested API responses in a Flux application?

I'm porting an existing app to Flux and I'm a bit confused about one topic. Say I have several API endpoints that return two- or three-level nested objects.

For example, GET /articles may return a JSON response of schema

articles: article*

article: {
  author: user,
  likers: user*
  primary_collection: collection?
  collections: collection*
}

collection: {
  curator: user
}

As you see, there are all kinds of users at different levels of nesting:

  • articles[i].author
  • articles[i].likers[i]
  • articles[i].primaryCollection.curator
  • articles[i].collections[i].curator

If I want to update UserStore with fresh data any time articles are fetched, I'd have to write a monstrous method that checks all nested entities on article API response. Moreover, there would be a lot of duplication because there are also other API endpoints with different schemas, and sometimes articles are embedded inside users (e.g. GET /user/published).

Is there a cleaner way for Flux stores to extract nested entities out of all API responses?


Source: (StackOverflow)

how to set ajax data fetching in flux?

I'm working on my first FLUX app and stumbled upon this problem. I want to get data from the server and pass it down to my component.

Say i have a component method ...

loadMore() {
  AppActions.getCards();
}

... and a store:

$.ajax({
  url: '../data.json',
  dataType: "json",
  success: function (data) {
    // ???
  }.bind(this),
  error: function (xhr, status, err) {
    console.error(status, err.toString());
  }.bind(this)
});

not quite sure how to do it properly. inside the ajax this is obviously undefined, also can't return value from it, or can i?

pretty sure it's trivial, but would be really grateful for an advice


Source: (StackOverflow)