Communication between components

Here's my situation, I am very new to react / flow and just started playing with it. My toy project is a simple library app. My current state looks like this:

  • I have a component called "Login". This component is only responsible for keeping the current user logged in to work with the latest Borrow / Return buttons in the library. Thus, the user enters a name that will be stored in the session store at the moment.
  • my other component is called Library, which contains the main logic of my application.

I am trying to figure out how to redraw my library component if I change the current user. Since my first project, I don't want to play with proper authentication or create a router. So I just created a login form and whenever the user enters their name and logs in, I display the library application in the DOM.

Login = React.createClass({

  _handleSubmit: function () {

    var inp = this.refs.login.getDOMNode();

    sessionStorage.setItem("username", inp.value);
    console.info('User Credentials saved to SessionStorage');
    inp.value = '';

    React.renderComponent(
      <Library />,
      document.querySelector('#content')
    );
  },

  render: function () {
    return (
      <div className="panel panel-default">
        blabla
                  <button className="btn btn-default" type="button" onClick={this._handleSubmit} >
                    Login
                  </button>
        blabla
      </div>
    );
  }
});

      

This works well, but I think it is far from the optimal approach. When I login again, react to re-render new instance from library component to DOM node. I don't know much about destructuring at all, and I think this is bad :( I know the react will not add, but erase and populate the node, but event handlers will probably stay, etc.

So what could be a possible good solution for my situation?

I have 3 possible solutions.

  • Either I have to design an event system to be able to notify the Library component if I re-enroll with another user to re-process myself, or
  • I could create parent-child relationships on login and in the library, so when I change the state of the Login component, the library application will be re-shown as well.
  • Call an action that will update the component
  • Stick with the current

:) Thanks for any answer, Cheers

Hint:

app.js

'use strict';
var React = require('react'),
    Login = require('./components/Login.jsx');

// Dev-tools
window.React = React;

React.renderComponent(
  Login(),
  document.querySelector('#login')
);

      

Login.jsx

said upper

Library.jsx

/** @jsx React.DOM */
'use strict';
var React = require('react'),
    BookShelf = require('./BookShelf.jsx'),
    Store = require('../stores/Store'),
    Library;

/**
 * Gets state from Storage
 * @returns {{books: BookCollection, users: UserCollection, categories: CategoryCollection}}
 */
function getState() {
  var state = Store.getAll();
  return {
    books: state.books,
    users: state.users,
    categories: state.categories
  };
}

Library = React.createClass({
  getInitialState: function() {
    return getState();
  },
  componentDidMount: function() {
    Store.addChangeListener(this._onChange);
    Store.initialize();
  },
  componentWillUnmount: function() {
    Store.removeChangeListener(this._onChange);
  },
  _onChange: function() {
    this.setState(getState());
  },
  render: function() {
    return (
      <div>
        <BookShelf
          books={this.state.books}
          users={this.state.users}
          categories={this.state.categories}
        />
      </div>
    );
  }
});

module.exports = Library;

      

+1


source to share


1 answer


If it's a Flux app, you want to take all that app logic and app state and move it to a store (or multiple stores).

Right now, it looks like you are doing this just fine for library related things. I would rename this LibraryStore. But you probably want AppStore or UserStore or SessionStore or something that has logic and data related to login, current user and auth token.



So, once the user is logged in, yes, you would want to create an Action (option # 3) so that all the different stores in your application know that your user is logged in, but primarily to inform the AppStore. Then your top-level views can listen to the AppStore and decide what to display. If you're using React's event model, you don't need to worry about cleaning up your event handlers. The flow controller views do not use the React model, so we have to clear them when unmounting.

Some of your difficulties may arise when modeling processes that are asynchronous. For example, authentication will require a server call and your new action will be created in the success / error callback for that call. To simulate this against localStorage, you can make a storage sync request and then invoke one of two different success / failure actions.

+5


source







All Articles