redux#compose TypeScript Examples

The following examples show how to use redux#compose. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: App.store.tsx    From tezos-academy with MIT License 6 votes vote down vote up
export function configureStore(preloadedState: any) {
  const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ trace: true, traceLimit: 25 })
    : compose

  const store: Store<State> = offline(storeOfflineConfig)(createStore)(
    reducers(history) as any,
    preloadedState,
    composeEnhancer(
      applyMiddleware(routerMiddleware(history)),
      applyMiddleware(thunk),
      applyMiddleware(reduxOfflineThunkMiddleware()),
    ),
  )

  return store
}
Example #2
Source File: index.ts    From idena-pocket with MIT License 6 votes vote down vote up
store = (() => {
	const store = createStore(
		combineReducers({
			router: connectRouter(history),
			app: rootReducer(defaultState)
		}),
		compose(
			applyMiddleware(routerMiddleware(history), ...middlewares),
			...(process.env.NODE_ENV === 'development' && devtools
				? [devtools()]
				: [])
		)
	)

	if ((module as any).hot) {
		// Enable Webpack hot module replacement for reducers
		;(module as any).hot.accept('../reducer', () => {
			const nextRootReducer = require('../reducer')
			store.replaceReducer(nextRootReducer)
		})
	}

	return store
})()
Example #3
Source File: store.ts    From farrow with MIT License 6 votes vote down vote up
createReduxDevtoolsEnhancer = (devtools: boolean = true, name?: string, enableLogger = false) => {
  const composeEnhancers =
    // tslint:disable-next-line: strict-type-predicates
    devtools && typeof window === 'object' && (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
      ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
          name,
        })
      : compose

  const enhancer = enableLogger ? composeEnhancers(applyMiddleware(createLogger())) : composeEnhancers()

  return enhancer
}
Example #4
Source File: configureStore.ts    From firebase-tools-ui with Apache License 2.0 6 votes vote down vote up
export default function configureStore(): Store<AppState> {
  const composeEnhancers =
    (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
  const sagaMiddleware = createSagaMiddleware();
  const store = createStore(
    rootReducer,
    composeEnhancers(applyMiddleware(sagaMiddleware))
  );
  sagaMiddleware.run(rootSaga);
  return store;
}
Example #5
Source File: serverAdmin.ts    From clearflask with Apache License 2.0 6 votes vote down vote up
static createStoreMiddleware(isProject: boolean, name: string): StoreEnhancer {
    var storeMiddleware = isProject
      ? applyMiddleware(thunk, reduxPromiseMiddleware, loadingBarMiddleware())
      : applyMiddleware(thunk, reduxPromiseMiddleware);
    if (!windowIso.isSsr) {
      const composeEnhancers =
        windowIso['__REDUX_DEVTOOLS_EXTENSION_COMPOSE__']
          ? windowIso['__REDUX_DEVTOOLS_EXTENSION_COMPOSE__']({
            serialize: true,
            name,
          })
          : compose;
      storeMiddleware = composeEnhancers(storeMiddleware);
    }
    return storeMiddleware;
  }
Example #6
Source File: configureStore.ts    From che-dashboard-next with Eclipse Public License 2.0 6 votes vote down vote up
export default function configureStore(history: History, initialState?: AppState): Store {
  const middleware = [
    thunk,
    routerMiddleware(history)
  ];

  const rootReducer = combineReducers({
    ...reducers,
    router: connectRouter(history)
  });

  const enhancers: any[] = [];
  const windowIfDefined = typeof window === 'undefined' ? null : window as any;
  if (windowIfDefined && windowIfDefined.__REDUX_DEVTOOLS_EXTENSION__) {
    enhancers.push(windowIfDefined.__REDUX_DEVTOOLS_EXTENSION__() as any);
  }

  return createStore(
    rootReducer,
    initialState,
    compose(applyMiddleware(...middleware), ...enhancers)
  );
}
Example #7
Source File: createStore.ts    From diagram-maker with Apache License 2.0 6 votes vote down vote up
export default function createStore<NodeType, EdgeType>(
  initialData?: DiagramMakerData<NodeType, EdgeType>,
  consumerRootReducer?: Reducer<DiagramMakerData<NodeType, EdgeType>, DiagramMakerAction<NodeType, EdgeType>>,
  consumerEnhancer?: StoreEnhancer,
  actionInterceptor?: ActionInterceptor<NodeType, EdgeType>,
): Store<DiagramMakerData<NodeType, EdgeType>> {
  const interceptorMiddleware = applyMiddleware(createInterceptorMiddleware(actionInterceptor));
  const undoMiddleware = applyMiddleware(getUndoMiddleware());
  const middleware = compose(interceptorMiddleware, undoMiddleware);
  const composedEnhancer = consumerEnhancer
    ? compose(middleware, consumerEnhancer)
    : middleware;

  /**
   * FIXME: Due to this issue: https://github.com/Microsoft/TypeScript/issues/21592
   * The below line needs an "any" typecast. It throws a type error for excessive
   * stack depth otherwise. Also, note that due to the type signatures on the function
   * declaration, type safety is lost within this method, but is retained everywhere else.
   * Remove this when typescript fixes it.
   */

  return reduxCreateStore(
    sequenceReducers<DiagramMakerData<NodeType, EdgeType>, DiagramMakerAction<NodeType, EdgeType>>(
      getRootReducer(),
      layoutReducer,
      consumerRootReducer,
    ),
    initialData as any,
    composedEnhancer,
  );
}
Example #8
Source File: modelStore.ts    From foca with MIT License 6 votes vote down vote up
protected getCompose(customCompose: CreateStoreOptions['compose']): Compose {
    if (customCompose === 'redux-devtools') {
      if (process.env.NODE_ENV !== 'production') {
        return (
          /** @ts-expect-error */
          (typeof window === OBJECT
            ? window
            : /* istanbul ignore next */
            typeof global === OBJECT
            ? global
            : {})['__REDUX_DEVTOOLS_EXTENSION_COMPOSE__'] || compose
        );
      }

      return compose;
    }

    return customCompose || compose;
  }
Example #9
Source File: store.test.ts    From foca with MIT License 6 votes vote down vote up
test('Get custom compose', () => {
  // @ts-expect-error
  const get: typeof store.getCompose = store.getCompose.bind(store);

  expect(get(void 0)).toBe(compose);
  expect(get(compose)).toBe(compose);

  const customCompose = (): StoreEnhancer => '' as any;
  expect(get(customCompose)).toBe(customCompose);

  const devtoolsComposer = composeWithDevTools({
    name: 'x',
  });
  expect(get(devtoolsComposer)).toBe(devtoolsComposer);
  expect(get(composeWithDevTools)).toBe(composeWithDevTools);

  expect(get('redux-devtools')).toBe(compose);

  // @ts-expect-error
  globalThis['__REDUX_DEVTOOLS_EXTENSION_COMPOSE__'] = customCompose;
  expect(get('redux-devtools')).toBe(customCompose);

  const prevEnv = process.env.NODE_ENV;
  process.env.NODE_ENV = 'production';
  expect(get('redux-devtools')).toBe(compose);
  process.env.NODE_ENV = prevEnv;
});
Example #10
Source File: App.tsx    From msteams-meetings-template with MIT License 6 votes vote down vote up
store = createStore(
  createRootReducer(hist),
  compose(
    applyMiddleware(
      routerMiddleware(hist),
      createAuthMiddleware(),
      createMeetingMiddleware()
    )
  )
)
Example #11
Source File: configureStore.ts    From tezos-link with Apache License 2.0 6 votes vote down vote up
export function configureStore(preloadedState: any) {
  const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
  const store = createStore(
    rootReducer(history),
    preloadedState,
    composeEnhancer(applyMiddleware(routerMiddleware(history)), applyMiddleware(thunk))
  )

  return store
}
Example #12
Source File: store.ts    From hamagen-react-native with MIT License 6 votes vote down vote up
export default function () {
  if (storeInstance) {
    return storeInstance;
  }

  const configOffline = {
    ...offlineConfig,
    rehydrate: true,
    persistOptions: {
      whitelist: []
    }
  };

  storeInstance = createStore(reducers, {}, compose(applyMiddleware(thunkMiddleware), offline(configOffline)));

  return storeInstance;
}
Example #13
Source File: store.ts    From slice-machine with Apache License 2.0 6 votes vote down vote up
export default function configureStore(
  preloadedState: Partial<SliceMachineStoreType> = {}
): { store: Store<SliceMachineStoreType>; persistor: Persistor } {
  const middlewares = [sagaMiddleware, routerMiddleware];
  const enhancers = [applyMiddleware(...middlewares)];

  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  const composeEnhancers =
    process.env.NODE_ENV !== "production" &&
    typeof window === "object" &&
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
      ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
      : compose;

  const rootReducer = createReducer();

  const persistedReducer = persistReducer(persistConfig, rootReducer);
  const store: Store<SliceMachineStoreType> = createStore(
    persistedReducer,
    preloadedState,
    // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-call
    composeEnhancers(...enhancers)
  );
  const persistor = persistStore(store);
  sagaMiddleware.run(rootSaga);

  return { store, persistor };
}
Example #14
Source File: store.ts    From rusty-chat with MIT License 6 votes vote down vote up
export default function configureStore(): any {
    const sagaMiddleware = createSagaMiddleware();
    const store = createStore(rootReducer, compose(applyMiddleware(routerMiddleware(history), sagaMiddleware)));

    sagaMiddleware.run(apiSaga);
    sagaMiddleware.run(userSaga);
    sagaMiddleware.run(feedSaga);

    return store;
}
Example #15
Source File: reduxDevToolsCompose.ts    From reactant with MIT License 6 votes vote down vote up
getComposeEnhancers = (
  enableReduxDevTools: boolean,
  reduxDevToolsOptions?: ReduxDevToolsOptions
) => {
  try {
    const reduxDevToolsCompose = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;
    return typeof reduxDevToolsCompose === 'function' && enableReduxDevTools
      ? reduxDevToolsCompose({
          serialize: true,
          actionSanitizer: (action: any) =>
            action._reactant === actionIdentifier
              ? {
                  ...action,
                  type: `@@reactant/${action.type}/${action.method}`,
                }
              : action,
          ...reduxDevToolsOptions,
        })
      : compose;
  } catch (e) {
    return compose;
  }
}
Example #16
Source File: App.ts    From YoutubeLiveApp with MIT License 6 votes vote down vote up
constructor(app: App) {
    this.app = app;
    this.app.on("ready", this.onReady);
    this.app.on("window-all-closed", this.onWindowAllClosed);

    const packageJson = fs.readFileSync(packageJsonPath);
    const packageJsonObject = JSON.parse(packageJson.toString("utf-8"));

    this.version = packageJsonObject.version;

    this.bouyomiChan = new BouyomiChan({
      port: this.bouyomiChanPort,
    });

    const initialState = resumeData();
    this.isAlwaysOnTop = !!initialState.isAlwaysOnTop;
    this.serverRunning = !!initialState.fixedChatUrl;
    const reducer = combineReducers({ app: createAppReducer(initialState), chat: createChatReducer(chatInitialState) });

    const myCreateStore = compose(applyMiddleware(MainProcessMiddleware()))(createStore);

    this.store = myCreateStore(reducer);
  }
Example #17
Source File: store.ts    From dh-web with GNU General Public License v3.0 5 votes vote down vote up
composeEnhancers = process.browser &&
    window["__REDUX_DEVTOOLS_EXTENSION_COMPOSE__"] as typeof compose || compose
Example #18
Source File: index.ts    From multisig-react with MIT License 5 votes vote down vote up
composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
Example #19
Source File: provider.reducer.ts    From multisig-react with MIT License 5 votes vote down vote up
providerReducerTests = () => {
  describe('Provider List Actions[fetchProvider -> addProvider]', () => {
    let store
    beforeEach(() => {
      const reducers = combineReducers({
        [PROVIDER_REDUCER_ID]: providerReducer,
      })
      const middlewares = [thunk]
      const enhancers = [applyMiddleware(...middlewares)]
      store = createStore(reducers, compose(...enhancers))
    })

    it('reducer should return default Provider record when no provider is loaded', () => {
      // GIVEN
      const emptyProvider = {
        name: '',
        loaded: false,
        available: false,
        account: '',
        network: 0,
      }

      // WHEN
      processProviderResponse(store.dispatch, emptyProvider)
      const provider = store.getState()[PROVIDER_REDUCER_ID]

      // THEN
      expect(makeProvider(emptyProvider)).toEqual(provider)
    })

    it('reducer should return avaiable with its default value when is loaded but not available', () => {
      // GIVEN
      const providerLoaded = {
        name: 'SAFE',
        loaded: true,
        available: false,
        account: '',
        network: 0,
      }

      // WHEN
      processProviderResponse(store.dispatch, providerLoaded)
      const provider = store.getState()[PROVIDER_REDUCER_ID]

      // THEN
      expect(makeProvider(providerLoaded)).toEqual(provider)
    })

    it('reducer should return provider when it is loaded and available', () => {
      // GIVEN
      const providerLoaded = {
        name: 'SAFE',
        loaded: true,
        available: true,
        account: '',
        network: 0,
      }

      // WHEN
      processProviderResponse(store.dispatch, providerLoaded)
      const provider = store.getState()[PROVIDER_REDUCER_ID]

      // THEN
      expect(makeProvider(providerLoaded)).toEqual(provider)
    })
  })
}
Example #20
Source File: store.ts    From foodie with MIT License 5 votes vote down vote up
composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
Example #21
Source File: modelStore.ts    From foca with MIT License 5 votes vote down vote up
init(options: CreateStoreOptions = {}) {
    const prevStore = this.origin;
    const firstInitialize = !prevStore;

    if (!firstInitialize) {
      if (process.env.NODE_ENV === 'production') {
        throw new Error(`[store] 请勿多次执行'store.init()'`);
      }
    }

    this._isReady = false;
    this.reducer = this.combineReducers();

    const persistOptions = options.persist;
    let persistor = this.persistor;
    persistor && persistor.destroy();
    if (persistOptions && persistOptions.length) {
      persistor = this.persistor = new PersistManager(persistOptions);
      this.reducer = persistor.combineReducer(this.reducer);
    } else {
      persistor = this.persistor = null;
    }

    let store: Store;

    if (firstInitialize) {
      const enhancer: StoreEnhancer<any> = applyMiddleware.apply(
        null,
        (options.middleware || []).concat(modelInterceptor),
      );

      store = this.origin = createStore(
        this.reducer,
        options.preloadedState,
        this.getCompose(options.compose)(enhancer),
      );
      this.topic.publish('init');

      combine(store);
    } else {
      // 重新创建store会导致组件里的subscription都失效
      store = prevStore;
      store.replaceReducer(this.reducer);
    }

    if (persistor) {
      persistor.init(store, firstInitialize).then(() => {
        this.ready();
      });
    } else {
      this.ready();
    }

    return this;
  }
Example #22
Source File: store.ts    From mamori-i-japan-admin-panel with BSD 2-Clause "Simplified" License 5 votes vote down vote up
composeEnhancers =
  (windowIfDefined && windowIfDefined.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ||
  compose
Example #23
Source File: store.ts    From shadowsocks-electron with GNU General Public License v3.0 5 votes vote down vote up
store = createStore(
  persistedReducer,
  compose(
    applyMiddleware(thunk),
    (window as any).devToolsExtension ? (window as any).devToolsExtension() : (f: any) => f
  )
)
Example #24
Source File: configureStore.ts    From querybook with Apache License 2.0 5 votes vote down vote up
composeEnhancers =
    (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
Example #25
Source File: index.tsx    From majsoul-api with MIT License 5 votes vote down vote up
composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
Example #26
Source File: WebcontentsPreloadMiddleware.ts    From YoutubeLiveApp with MIT License 5 votes vote down vote up
export default function createSharedStore<State>(reducer: Reducer<State>) {
  const myCreateStore = compose(applyMiddleware(WebcontentsPreloadMiddleware()))(createStore);
  const store = myCreateStore(reducer);
  store.dispatch(RendererInitialize());
  return store;
}
Example #27
Source File: index.ts    From react_admin with MIT License 5 votes vote down vote up
composeEnhancers =
  typeof window === "object" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
        // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
      })
    : compose
Example #28
Source File: store.ts    From extension with MIT License 5 votes vote down vote up
enhancer = compose(applyMiddleware(thunk), DevTools.instrument())
Example #29
Source File: Provider.tsx    From nosgestesclimat-site with MIT License 5 votes vote down vote up
composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose