Skip to main content

Using Redux

Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently and share state.

The Gist

The whole state of your app is stored in an object tree inside a single store. The only way to change the state tree is to emit an action, an object describing what happened. To specify how the actions transform the state tree, you write pure reducers.

Instead of mutating the state directly, you specify the mutations you want to happen with plain objects called actions. Then you write a special function called a reducer to decide how every action transforms the entire application’s state.

Instead, there is just a single store with a single root reducing function.

Usage

Preferred way to use Redux is to create single store for Redapp - either in Main class or in designated one, with designated reducer handling actions and separate function for action creation. Actions are just simple JS object with type field and any additional fields.

export interface Data {
  message: string;
}

function reducer(state: Data = {message: 'a message'}, action) {
  switch (action.type) {
    case 'CHANGE_MSG':
      return {
        ...state,
        message: action.newVal
      };
    default:
      return state
  }
}

export class LocalStore {
  public store = createStore(reducer);

  getData(): Data {
    return this.store.getState();
  }

  setMessage(newVal: string) {
    const action = {type: "CHANGE_MSG", newVal: newVal};
    this.store.dispatch(action);
  }
}

Then store can be passed to other services, models and components to use shared state.

Working sample can be found in samples directory under com.sabre.redapp.example3.web.persistence name.