organizationsStore.tsx 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import Reflux from 'reflux';
  2. import OrganizationsActions from 'app/actions/organizationsActions';
  3. import {Organization} from 'app/types';
  4. type OrganizationsStoreInterface = {
  5. state: Organization[];
  6. loaded: boolean;
  7. onUpdate: (org: Organization) => void;
  8. onChangeSlug: (prev: Organization, next: Organization) => void;
  9. onRemoveSuccess: (slug: string) => void;
  10. get: (slug: string) => Organization | undefined;
  11. getAll: () => Organization[];
  12. remove: (slug: string) => void;
  13. add: (item: Organization) => void;
  14. load: (items: Organization[]) => void;
  15. };
  16. type OrganizationsStore = Reflux.Store & OrganizationsStoreInterface;
  17. const organizationsStoreConfig: Reflux.StoreDefinition & OrganizationsStoreInterface = {
  18. listenables: [OrganizationsActions],
  19. state: [],
  20. loaded: false,
  21. // So we can use Reflux.connect in a component mixin
  22. getInitialState() {
  23. return this.state;
  24. },
  25. init() {
  26. this.state = [];
  27. this.loaded = false;
  28. },
  29. onUpdate(org: Organization) {
  30. this.add(org);
  31. },
  32. onChangeSlug(prev: Organization, next: Organization) {
  33. if (prev.slug === next.slug) {
  34. return;
  35. }
  36. this.remove(prev.slug);
  37. this.add(next);
  38. },
  39. onRemoveSuccess(slug: string) {
  40. this.remove(slug);
  41. },
  42. get(slug: Organization['slug']) {
  43. return this.state.find((item: Organization) => item.slug === slug);
  44. },
  45. getAll() {
  46. return this.state;
  47. },
  48. remove(slug: Organization['slug']) {
  49. this.state = this.state.filter(item => slug !== item.slug);
  50. this.trigger(this.state);
  51. },
  52. add(item: Organization) {
  53. let match = false;
  54. this.state.forEach((existing, idx) => {
  55. if (existing.id === item.id) {
  56. item = {...existing, ...item};
  57. this.state[idx] = item;
  58. match = true;
  59. }
  60. });
  61. if (!match) {
  62. this.state = [...this.state, item];
  63. }
  64. this.trigger(this.state);
  65. },
  66. load(items: Organization[]) {
  67. this.state = items;
  68. this.loaded = true;
  69. this.trigger(items);
  70. },
  71. };
  72. const OrganizationsStore = Reflux.createStore(
  73. organizationsStoreConfig
  74. ) as OrganizationsStore;
  75. export default OrganizationsStore;