goatslacker / alt

Isomorphic flux implementation
http://alt.js.org/
3.45k stars 323 forks source link

Public Method returns state not store; am I guaranteed the Store is updated when the listener fires? #714

Open nawgz opened 7 years ago

nawgz commented 7 years ago

ExampleStore.js:

import ExampleActions from '../actions/ExampleActions';

class ExampleStore {
  constructor() {
    this.data = [];

    this.bindListeners({
      handleCreateData: ExampleActions.CREATE_Data,
    });

    this.exportPublicMethods({
      getSemanticDefinitions: this.getData,
    });
  }

  /* ACTION HANDLERS */
  handleCreateData(response) {
    if (response.status === 'success') {
      this.data.push(response.data);
    }
  }

  /* PUBLIC METHODS */
  getData() {
    console.dir(this);
    console.dir(this.state);
    return this.state.data;
  }
}

export default alt.createStore(ExampleStore, 'ExampleStore');

ExampleComponent.jsx:

import React from 'react';
import ExampleActions from '../alt/actions/ExampleActions';
import ExampleStore from '../alt/stores/ExampleStore';

class Example extends React.Component {
  constructor(props) {
    super(props);

    this.updateStore = this.updateStore.bind(this);
    this.storeChanged = this.storeChanged.bind(this);

    this.state = {
      data: ExampleStore.getData(),
    };
  }

  componentWillMount() {
    ExampleStore.listen(this.storeChanged);
  }

  componentWillUnmount() {
    ExampleStore.unlisten(this.storeChanged);
  }

  storeChanged(exampleStoreState) {
    this.setState({
      data: exampleStoreState.getData(), // can't do this obviously
      data: ExampleStore.getData(), // Is this guaranteed to have the updated state?
    });
  }

  updateStore(object) {
    ExampleActions.createData(object);
  }

  render() {
    // contains button you click that triggers updateStore with some object
  }
}

export default Example;

Question: when my listener gets fired, I wish to be able to use my public method instead of reading from the state directly. However, I am unsure that I am guaranteed ExampleStore itself has the updated. It seems to work, but I thought I would clarify so I don't get burned later.

Thanks.

pk1m commented 7 years ago

I've done it in the past like this and haven't had any inconsistencies pop up.