Initial data loading ReactJS
Asked Answered
H

1

7

I would like to perform some initial data loading when my first route is rendered (for example, i want to load a list of news articles)

I made a component called News.js which renders the articles. The problem i'm experiencing with the FLUX model is where to load this initial data.

The service i have made to load the data is the following: import request from 'superagent';

class NewsService {

  fetchArticles(callback) {
    request
      .get('http://localhost/articles')
      .accept('json')
      .end(function(err, res){
        console.log(err);
        var result = JSON.parse(res.text);
        callback(result);
      })
  }

}

export default new NewsService ();

This service has to be called somewhere. According to the ReactJS documentation i would perform this operation like this:

export default class News extends React.Component {

  constructor() {
    super();
    this.state = {
      _articles: []
    }
  }

  componentDidMount() {
    NewsService.fetchProjects(function(articles){
      // load articles in the state
      this.setState({_articles: _articles})
    });
  }

  render() {

      return (
          <section>
              <h1>Articles</h1>
              <ul>
                {this.state.articles.map((article) => {
                  <li>{article.title}</li>
                })}
              </ul>
          </section>
      )
  }
}

Now my question is, isn't this against the flux principle? Shouldn't the data be called as an Action which then stores it's data in a store such as NewsStore?

Should an action be like the following:

var NewsActions = {

  load: function() {
    NewsService.fetchProjects(function(articles){
      // store the articles in the NewsStore and dispatch afterwards          
    });
  },

  create: function(project) {
    AppDispatcher.dispatch({
      actionType: NewsConstants.ARTICLE_CREATE,
      project: project
    });
  },

  update: function(id, project) {
    AppDispatcher.dispatch({
      actionType: NewsConstants.ARTICLE_UPDATE,
      id: id,
      project: project
    })
  },

  destroy: function() {
    AppDispatcher.dispatch({
      actionType: NewsConstants.ARTICLE_DESTROY,
      id: id
    })
  }
};

export default NewsActions;

In the Chat-app example of reactjs they provide an API call example. However this API call is called on the application start up (in app.js) which is not applicable in my scenario as i would like to use routings. Would i load the data in the router then? (I am using react-router)

Any feedback regarding this matter or improvements of this code is more than welcome.

Herwick answered 8/9, 2015 at 16:39 Comment(0)
E
0

EDIT

isn't this against the flux principle?

Maybe, maybe not. Seems like Flux is pretty flexible. From what I understand, it's more of a framework of principles rather than a strict "protocol". It's hard to say, but it appears that both example you've given will work. Like you said, according to the docs, they recommend fetching the data in componentDidMount:

componentDidMount: function() {
    $.get(this.props.source, function(result) {
    // ...

However, in your example, you're simply moving that API call into a service, which can then interact with the store/dispatcher, etc., in order to be utilized across the entire application.

So what you've done is moved a nice chunk of your application logic to, essentially, its own module (well, a module that is a part of your dispatchers). It appears that it will meet your needs: it can be used across your app, and it can be pulled out or plugged back in as you see fit. I don't see anything wrong with it. Could it be against some principle of Flux? Maybe, maybe not. I doubt it matters, though.

ORIGINAL

I'm not well-versed in Flux architecture, but looking at one of Facebook's examples in their GitHub repo (specifically, Line 24 of TodoMVC):

function getTodoState() {
  return {
    allTodos: TodoStore.getAll(),
    areAllComplete: TodoStore.areAllComplete()
  };
}

Their example doesn't show how TodoStore interacts with the server, but it does look like for their initial state, they're simply querying the todos in the store, and then for changes, their listening for and emitting events.

So as far as getting the initial state, it looks like their example shows querying the store directly. Obviously since the time they made that example and now, there may have been changes, but it may be worth investigating some examples in the Flux repo to get an idea of how it was designed.

Elvieelvin answered 8/9, 2015 at 16:54 Comment(7)
This is indeed a great way. However i would like to know how they would fill initital data from the server into that store. I checked the Chat application which includes a API call, however here they just load the data in the main app.js which is not of any use if you have multiple pages github.com/facebook/flux/blob/….Herwick
Updated my original post with further details (sorry for extensive comment)Herwick
Would i also put the fetched result into the store?Herwick
@MaximGeerinck, if you didn't, then the rest of your app wouldn't have access to the results, right?Elvieelvin
I guess so, however, they will have to visit the page first before the store actually is filled which doesn't make sense then?Herwick
@MaximGeerinck, if other components are going to use that store data, then yes.Elvieelvin
Okay, and otherwise you don't use a store then? (Or it's not necessary)Herwick

© 2022 - 2024 — McMap. All rights reserved.