Question: How to update component when store data its updated

Question

How to update component when store data its updated

Answers 0
Added at 2016-04-25 09:04
Tags
Question

Hi I'm trying to understand reflux but I'm very newbie. I want to update my component <Content /> when <AddContent /> trigger my new content to my ContentStore but I don't know how. I console.log my variable _content at my ContentStore and I can see it. Thanks for the help!

Here is <Content /> that list all but never update:

import React from 'react';
import Reflux from 'reflux';
import ContentsStore from '../stores/ContentsStore';
import ContentsActions from '../actions/ContentsActions';

function getContents() {
  return {
    contents: ContentsStore.getContents(),
  }
}
var Contents = React.createClass({
  getInitialState: function() {
    return getContents()
  },
  render: function() {
    if (this.state.contents) {
      return <ul>
        {
          this.state.contents.map(function(content) {
            return <li key={content.id}>
              <strong>{content.id}</strong>
              <span> - {content.title} </span>
              <time>{content.date}</time>
            </li>
          })
        }
      </ul>
    }
    else {
      return (<p>There is no content</p>);
    }
  }
});

module.exports = Contents;

Here is ContentStore:

import Reflux from 'reflux';
import ContentsActions from '../actions/ContentsActions';

var _contents = [];

var defaultContents = function() {
  return [
    {"id": 1, "title": "Content 1", "text": "Lorem ipsum dolor sit amet", "date": "Mar 12 2012 10:00:00 AM" },
    {"id": 2, "title": "Content 4", "text": "Lorem ipsum dolor sit amet", "date": "Mar 12 2012 10:00:00 AM" },
    {"id": 3, "title": "Content 2", "text": "Lorem ipsum dolor sit amet", "date": "Mar 12 2012 10:00:00 AM" }
  ]
}
var ContentsStore = Reflux.createStore({
  init: function() {
    _contents = defaultContents();
  },
  getContents: function() {
    return _contents;
  },
  addContent: function(content) {
    _contents.push(content);
    console.log(_contents);
  },
});

export default ContentsStore;

Here is <AddContent /> that list all but never update:

import React from 'react';
import Reflux from 'reflux';
import _ from 'lodash';
import ContentsStore from '../stores/ContentsStore';
import ContentsActions from '../actions/ContentsActions';

var AddContent = React.createClass({
  mixins: [Reflux.connect(ContentsStore, 'imagestore')],
  getInitialState: function() {
    return {
      content: {
        id: Math.floor((Math.random() * 10000) + 1),
        title: '',
        date: new Date(),
      },
      errors: {},
    }
  },
  renderTextInput: function(id, label, help) {
    return this.renderField(id, label, help,
      <input type="text" id={id} ref={id} key={id} value={this.state.content[id]} onChange={this.handleChange.bind(this, id)}/>
    )
  },
  renderField: function(id, label, help, field) {
    return <div className={theClass('form-group', {'has-error': id in this.state.errors})}>
             <label htmlFor={id} className="label">{label}</label>
             {field}
             <small className="help">{help}</small>
          </div>
  },
  handleChange: function(field, e) {
    var thisContent = this.state.content;
    thisContent[field] = e.target.value;
    this.setState({content: thisContent});
  },
  handleSubmit: function(e) {
    e.preventDefault();
    var errors = {}
    var required = ['title'];
    // Check for required fields
    required.forEach(function(field) {
      if (!this.state.content[field]) {
        errors[field] = 'This field is required.'
      }
    }.bind(this));
    // Update the state with any errors
    this.setState({errors: errors});
    // If no errors, emit action to add it
    if (_.keys(errors).length === 0) {
      ContentsStore.addContent(this.state.content);
      // Refresh the form and errors
      this.setState({
        content: {},
        errors: {}
      });
    }
  },
  render: function() {
    return <div>
      <form onSubmit={this.handleSubmit}>
        {this.renderTextInput('title', 'Title', 'Title of the content')}
        <button type="submit">Add Content</button>
      </form>
    </div>
  }
});

module.exports = AddContent;

function theClass(staticClassName, conditionalClassNames) {
  var classNames = []
  if (typeof conditionalClassNames == 'undefined') {
    conditionalClassNames = staticClassName
  }
  else {
    classNames.push(staticClassName)
  }
  for (var className in conditionalClassNames) {
    if (!!conditionalClassNames[className]) {
      classNames.push(className)
    }
  }
  return classNames.join(' ')
}

Here is ActionStoreimport Reflux from 'reflux';

let ContentsActions = Reflux.createActions([
  'getContents',
  'addContent',
]);

export default ContentsActions;
Answers to

How to update component when store data its updated

Source Show
◀ Wstecz