0

following the Flux pattern I'm trying to update my component and pass some values (a string and a boolean in this specific case) via the store.

Flux Pattern

I could not find any non-hacky way to solve this yet i.e. using global vars in the Store and use a getter function in the Store which is called from the component on ComponentWillMount(), not a nice solution.

Here's a stripped down code example to show what im trying to achieve:

ExampleStore.js

import AppDispatcher from '../appDispatcher.jsx';
var displayimportError = false;
var importedID = '';
import axios from 'axios';

class ExampleStore extends EventEmitter {
  constructor() {
    super();
  }



importId(id) {
    let self = this;

    // fetch data from BE
    axios.get('foo.com').then(function(response) {
        if (response.data && response.data.favoriteEntries) {
            displayimportError = false;
        }
        self.emitChange();
    }).catch(function(error) {
        console.log(error);
        displayimportError = true;
        importedID = id;
        self.emitChange();
        // now update component and pass displayimportError and 
        // importedID.
        // best would to component.receiveUpdateFromStore(param); but 
        // it's giving receiveUpdateFromStore is not function back
      });

   }

}

var favObj = new ExampleStore();

AppDispatcher.register(function(payload) {
  var action = payload.action;
  switch (action.actionType) {
    case 'UPDATE_ID':
        favObj.importId(action.data);
        break;
}

return true;
});

export default favObj;

As mentioned in the Comment above the best solution in my eyes so far would be to call a function in the component from the store i.e component.receiveUpdateFromStore(param); and then update the component state within that function but even though they seem to be im/exported correctly to me it is returning receiveUpdateFromStore is undefined.

Any other idea how to solve this is appreciated.

//example component

   import React from 'react';
   import ReactDom from 'react-dom';
   import ExampleStore from '../stores/ExampleStore.jsx';

   class ExampleComponent extends React.Component {


    constructor(props) {
        super(props);
    }

    receiveUpdateFromStore(param) {
        this.setState({'exampleText': param.text, 'exampleBoolean': param.bool});
    }


     render() {

        return <div className="foo">bar</div;
     }
    }
    export default ExampleComponent;

Any idea how to pass data from store to a component and update component state in a nice way?

4
  • Use connect from react-redux and give it mapStateToProps mapping function, that's how you retrieve data from the store Commented Sep 23, 2017 at 19:25
  • there's no redux included in the project yet and i would like to keep it that way, it's even noticed in the flux paradigm above, i guess i'm just missing out on the functionality Commented Sep 23, 2017 at 19:28
  • You are just making it harder on yourself unneccessarily Commented Sep 23, 2017 at 21:32
  • Although it is not an answer to the question, I also strongly advise you to use Redux instead if you worry about consistency/a "nice solution", like you say. Commented Sep 23, 2017 at 21:39

1 Answer 1

1

I would hang your store state on the store class instance itself -- something like this.state.displayimportError = true -- and then have the component subscribe to the store:

import React from 'react';
import ExampleStore from '../stores/ExampleStore.jsx';

class ExampleComponent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      importError: ExampleStore.state.displayimportError,
    };
  }

  componentWillMount() {
    ExampleStore.on( 'change', this.updateState );
  }

  componentWillUnmount() {
    ExampleStore.removeListener( 'change', this.updateState ); 
  }

  updateState = () => {
    this.setState( state => ({
      importError: ExampleStore.state.displayimportError,
    })
  }

  render() {
    return <div>{ this.state.importError }</div>
  }
}

NOTE: Above code untested, and also using class properties/methods for binding updateState.

Sign up to request clarification or add additional context in comments.

1 Comment

btw you'll quickly find that this is a lot of boilerplate. i'd recommend abstracting the relevant bits of code out into a subscribeTo( ExampleStore ) higher-order component or something like that. though i'll also throw my 2¢ into the pot to say that we left our home-grown flux architecture for redux a while back and have been very happy!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.