Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
nawgz opened this issue May 16, 2017 · 1 comment

Comments

@nawgz
Copy link

nawgz commented May 16, 2017

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
Copy link

pk1m commented May 22, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants