Architecture: Flux

Architecture: Flux

Introduction

Flux was born within the Facebook team as a solution for scalability problems in complex web applications. Flux has a unidirectional data flow approach that simplifies debugging in comparison to the MVC approach.

How?

Flux is made up for:

  • Action creators: create and return appropriate actions.

  • Action types: represents a specific action like creating or deleting a resource.

  • Dispatcher: a function that receives an action, performs the appropriate logic, and sends the result to the store.

  • Store: the project's source of truth. It contains all the data and that data notifies the view that it needs to be updated.

  • View: the UI of the app. When a user interacts with the UI, it dispatches an action.

Code example

Action types

const ADD_TASK = 'ADD_TASK';
const DELETE_TASK = 'DELETE_TASK';

Action creator

const addTask = (task) => {
  return {
    type: ADD_TASK,
    payload: task
  };
};

const deleteTask = (taskId) => {
  return {
    type: DELETE_TASK,
    payload: taskId
  };
};

Dispatcher

const dispatcher = (action) => {
  // Do someting
  store.dispatch(action);
};

Store

const initialState = {
  tasks: []
};

const taskReducer = (state = initialState, action) => {
  switch (action.type) {
    case ADD_TASK:
      return {
        ...state,
        tasks: [...state.tasks, action.payload]
      };
    case DELETE_TASK:
      return {
        ...state,
        tasks: state.tasks.filter(task => task.id !== action.payload)
      };
    default:
      return state;
  }
};

View

const handleCompleteTodo = () => {
  dispatcher(addTask);
};

<button onClick={handleAddTodo}>

Thanks to the unidirectional data flow, you can travel through time and find that bug or understand that code followingg the trail of it.