Blaise
Blaise

Reputation: 23

NgRx Store state for tabs

I am trying to implement something similar to the browser tabs in my application. Currently I'm creating a new key in the store for every opened tab and separately storing the current tab's id. Currently my store's state is similar to this:

{
  currentTab: 0,
  0: {
       url: 'http://google.com'
  }
  1: {
       url: 'http://twitter.com'
  }
}

Since I am pretty new to ngrx, I hope you can tell whether this is the right approach for this kind of things.

Thanks a lot!

Upvotes: 1

Views: 2488

Answers (1)

Felix Lemke
Felix Lemke

Reputation: 6488

You should actually store your tabs with @ngrx/entity. UI state definitely belongs to the store, see here.

Your reducer could look like

import { createEntityAdapter, EntityState } from '@ngrx/entity';

import { TabsActions, TabsActionTypes } from '../actions';
import { Tab } from '../../models/tab';

export const adapter = createEntityAdapter<Tab>({
  selectId: tab => tab.id,
  sortComparer: (tabA, tabB) => tabA.id === tabB.id ? 0 : tabA.id > tabB.id ? 1 : -1
});

export interface State extends EntityState<Tab> {
  currentTab: number
}
export const initialState = adapter.getInitialState({
  currentTab: 0
});

export function reducer(state = initialState, action: TabsActions) {
  switch (action.type) {
    case TabsActionTypes.Add:
      return adapter.add(action.payload, state);

    case TabsActionTypes.Close:
      return adapter.remove(action.payload, state);

    case TabsActionTypes.SwitchTab:
      return { ...state, currentTab: action.payload }

    default:
      return state;
  }
}

With the actions defined as

import { Action } from '@ngrx/store';
import { Tab } from '../../models/tab';

export enum TabsActionTypes {
  Add = '[Tabs] Add',
  Close= '[Tabs] Close',
  SwitchTab = '[Tabs] Switch'
}

export class AddTab implements Action {
  readonly type = TabsActionTypes.Add;
  constructor(public payload: Tab) {}
}

// Define other actions (CloseTab, SwitchTab) in a similar way

export type TabsActions =
  AddTab |
  CloseTab |
  SwitchTab;

Upvotes: 2

Related Questions