Search code examples
javascriptreactjsflux

Does React Flux library Alt use React's state?


After completing the guide on the Alt site I am confused if Alt uses Reacts state to set properties? In part 3 - using Stores, it says

Instance variables defined anywhere in the store will become the state.

It then puts a variable in the store:

this.locations = [];

Yet if I go into the main React component and log the state, after locations is given data of course, I get undefined except on the props?

loggState() {
  console.log(this.state); // undefined
  console.log(this.locations); // undefined
  console.log(this.props.locations); // [object][object]..
}

Can anyone explain the relationship between states and props when using Alt?


Solution

  • In Alt—and indeed most Flux implementations—the store is a totally different part of your application to your components.

    A component subscribes to changes in a store, then uses the changed data to update its local state, causing it to re-render.

    We derive the initial state of components that use the LocationStore from whatever the store's state is when we instantiate the component.

    getInitialState() {
      return LocationStore.getState();
    },
    

    Then we set up a subscription, listening for changes to the store.

    componentDidMount() {
      LocationStore.listen(this.onChange);
    },
    

    And finally, we use the subscription handler to apply these changes to the component's local state. The way you decide to apply each update is totally up to you.

    onChange(state) {
      this.setState(state);
    },
    

    Each time we call this.setState with a new state, the component will re-render.

    You could also use a higher-order component to subscribe to the store, then covert the store's state to props and pass them down to a wrapped component, instead. In which case, your component wouldn't need to be stateful at all.