Search code examples
reactjsreduxreact-reduxfluxreactjs-flux

Is this Flux architecture?


This is how I've been organizing my React / Redux projects because it's how they did it in the tutorial I followed. Is this what Flux architecture is and if not what would you call this?

  • First I call a function in my component that's defined in the action file
  • This function does an ajax request to get info from an API
  • Then it fires off an action creator
  • The reducer listens for action creators and once one is detected it executes a function that updates the state

Here's an example:

Component

class List extends React.Component {
  componentDidMount() {
    this.props.getPosts();
  }
  // etc...
}

const mapStateToProps = state => {
  return {
    posts: state.posts
  };
};

const mapDispatchToProps = dispatch => {
  return {
    getPosts: () => dispatch(actions.getPosts())
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(List);

Action

const postsLoaded = posts => {
  return {
    type: actionTypes.POSTS_LOADED,
    posts: posts
  };
};

export const getPosts = () => {
  return dispatch => {
    axios
      .get('http://api.something.com/posts', {})
      .then(response => {
        dispatch(postsLoaded(response.posts));
      })
      .catch(e => {
        console.error(e);
      });
  };
};

Reducer

const setPosts = (prevState, action) => {
  return {
    ...prevState,
    ...action.posts
  };
};

const reducer = (prevState = {}, action) => {
  switch (action.type) {
    case actionTypes.POSTS_LOADED:
      return setPosts(prevState, action);
    default:
      return prevState;
  }
};

export default reducer;

Solution

  • Flux is a design pattern. Redux is one of several libraries that implement Flux. The intent is NOT for you to "use Redux to implement Flux", but rather "use the Flux pattern by using Redux".

    You can find a much better description in the docs below, but in simplest terms, the Flux architecture is based on a unidirectional data flow, which means that each piece receives data from one place, and outputs changes to another. The intent of this pattern is to eliminate "spaghetti code", where various parts of the application pass data in many different directions, which can eventually become very difficult to trace.

    In other words, your components are the "View" in the diagram below.

    • Redux store gives state to your component
    • Your component renders something, and when a user performs an action, the component creates an action and gives it to the dispatcher.
    • The dispatcher finds the reducer that can handle your action, and gives the result to the store.

    And the cycle repeats.

    flow architecture This image and an in-depth overview of Flux can be found here.