redux#createStore TypeScript Examples

The following examples show how to use redux#createStore. 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: reducer.test.ts    From cuiswap with GNU General Public License v3.0 7 votes vote down vote up
describe('mint reducer', () => {
  let store: Store<MintState>

  beforeEach(() => {
    store = createStore(reducer, {
      independentField: Field.CURRENCY_A,
      typedValue: '',
      otherTypedValue: ''
    })
  })

  describe('typeInput', () => {
    it('sets typed value', () => {
      store.dispatch(typeInput({ field: Field.CURRENCY_A, typedValue: '1.0', noLiquidity: false }))
      expect(store.getState()).toEqual({ independentField: Field.CURRENCY_A, typedValue: '1.0', otherTypedValue: '' })
    })
    it('clears other value', () => {
      store.dispatch(typeInput({ field: Field.CURRENCY_A, typedValue: '1.0', noLiquidity: false }))
      store.dispatch(typeInput({ field: Field.CURRENCY_B, typedValue: '1.0', noLiquidity: false }))
      expect(store.getState()).toEqual({ independentField: Field.CURRENCY_B, typedValue: '1.0', otherTypedValue: '' })
    })
  })
})
Example #2
Source File: test-utils.ts    From pipeline-editor with Apache License 2.0 7 votes vote down vote up
export function createPropertiesStore({ name }: { name: string }, value: any) {
  const initialState = {
    propertiesReducer: {
      [name]: value,
    },
  };

  function reducer(state: any) {
    return state;
  }

  return createStore(reducer, initialState);
}
Example #3
Source File: create-store.ts    From anthem with Apache License 2.0 6 votes vote down vote up
configureStore = () => {
  const reduxStore = createStore(
    rootReducer,
    composeWithDevTools(applyMiddleware(...middleware)),
  );

  // @ts-ignore
  epicMiddleware.run(rootEpic);

  return reduxStore;
}
Example #4
Source File: emu-renderer.tsx    From kliveide with MIT License 6 votes vote down vote up
// ------------------------------------------------------------------------------
// --- Register the main services

// --- Application state store (redux)
registerService(
  STORE_SERVICE,
  new KliveStore(
    createStore(
      combineReducers(appReducers),
      getInitialAppState(),
      applyMiddleware(forwardToMainMiddleware)
    )
  )
);
Example #5
Source File: reducer.test.ts    From cuiswap with GNU General Public License v3.0 6 votes vote down vote up
describe('swap reducer', () => {
  let store: Store<SwapState>

  beforeEach(() => {
    store = createStore(reducer, {
      [Field.OUTPUT]: { currencyId: '' },
      [Field.INPUT]: { currencyId: '' },
      typedValue: '',
      independentField: Field.INPUT,
      recipient: null
    })
  })

  describe('selectToken', () => {
    it('changes token', () => {
      store.dispatch(
        selectCurrency({
          field: Field.OUTPUT,
          currencyId: '0x0000'
        })
      )

      expect(store.getState()).toEqual({
        [Field.OUTPUT]: { currencyId: '0x0000' },
        [Field.INPUT]: { currencyId: '' },
        typedValue: '',
        independentField: Field.INPUT,
        recipient: null
      })
    })
  })
})
Example #6
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 #7
Source File: configureStore.ts    From atorch-console with MIT License 6 votes vote down vote up
configureStore = () =>
  createStore(
    createRootReducer(history),
    undefined,
    composeEnhancers(
      applyMiddleware(
        routerMiddleware(history), // connected-react-router
        thunk as ThunkMiddleware<RootState>, // redux-thunk
      ),
    ),
  )
Example #8
Source File: configureStore.ts    From mops-vida-pm-watchdog with MIT License 6 votes vote down vote up
configureStore = () =>
  createStore(
    createRootReducer(history),
    undefined,
    composeEnhancers(
      applyMiddleware(
        routerMiddleware(history), // connected-react-router
        thunk as ThunkMiddleware<RootState>, // redux-thunk
      ),
    ),
  )
Example #9
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 #10
Source File: reducer.test.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
describe('swap reducer', () => {
  let store: Store<SwapState>;

  beforeEach(() => {
    store = createStore(reducer, {
      [Field.OUTPUT]: { currencyId: '' },
      [Field.INPUT]: { currencyId: '' },
      typedValue: '',
      independentField: Field.INPUT,
      recipient: null,
    });
  });

  describe('selectToken', () => {
    it('changes token', () => {
      store.dispatch(
        selectCurrency({
          field: Field.OUTPUT,
          currencyId: '0x0000',
        }),
      );

      expect(store.getState()).toEqual({
        [Field.OUTPUT]: { currencyId: '0x0000' },
        [Field.INPUT]: { currencyId: '' },
        typedValue: '',
        independentField: Field.INPUT,
        recipient: null,
      });
    });
  });
});
Example #11
Source File: reducer.test.ts    From sybil-interface with GNU General Public License v3.0 6 votes vote down vote up
describe('swap reducer', () => {
  let store: Store<UserState>

  beforeEach(() => {
    store = createStore(reducer, initialState)
  })

  describe('updateVersion', () => {
    it('has no timestamp originally', () => {
      expect(store.getState().lastUpdateVersionTimestamp).toBeUndefined()
    })
    it('sets the lastUpdateVersionTimestamp', () => {
      const time = new Date().getTime()
      store.dispatch(updateVersion())
      expect(store.getState().lastUpdateVersionTimestamp).toBeGreaterThanOrEqual(time)
    })
    it('sets allowed slippage and deadline', () => {
      store = createStore(reducer, {
        ...initialState,
        userDeadline: undefined,
        userSlippageTolerance: undefined,
      } as any)
      store.dispatch(updateVersion())
    })
  })
})
Example #12
Source File: devStoreConfig.ts    From react-app-architecture with Apache License 2.0 6 votes vote down vote up
devStoreConfig = (preloadedState: Partial<RootState>): Store => {
  const store = createStore(
    rootReducer,
    preloadedState,
    applyMiddleware(thunk, logger, crashReporter),
  );

  // @ts-ignore
  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    // @ts-ignore
    module.hot.accept('../reducers', () => {
      const nextRootReducer = require('../reducers');
      store.replaceReducer(nextRootReducer);
    });
  }

  return store;
}
Example #13
Source File: store.ts    From brick-design with MIT License 6 votes vote down vote up
export function createLegoStore(
  config: ConfigType,
  customReducer?: ReducerType,
  warn?: WarnType,
) {
  if (warn) setWarn(warn);
  if (getBrickdConfig() && !config) {
    throw Error('config未初始化');
  } else if (!getBrickdConfig()) {
    setBrickdConfig(config);
  }
  if (getStore()) return getStore();

  const store = createStore(
    combineReducers(reducer, customReducer),
    (window as any).__REDUX_DEVTOOLS_EXTENSION__ &&
      (window as any).__REDUX_DEVTOOLS_EXTENSION__(),
  );
  const legoStore = { ...store, getPageState };
  setStore(legoStore);
  return legoStore;
}
Example #14
Source File: messages.spec.ts    From camus with GNU Affero General Public License v3.0 6 votes vote down vote up
describe('Test messages slice of Redux store', () => {
    it('can add a chat message', () => {
        // Setup
        const store = createStore(reducer);

        // Test
        const chatMessage = {
            from: 'Major Tom',
            timestamp: 10101010,
            text: 'Hello world!',
        };
        store.dispatch(addChatMessage(chatMessage));

        // Get result
        const state = store.getState();

        // Verify result
        expect(state).includes(chatMessage);
    });
});
Example #15
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 #16
Source File: reducer.test.ts    From cheeseswap-interface with GNU General Public License v3.0 6 votes vote down vote up
describe('swap reducer', () => {
  let store: Store<UserState>

  beforeEach(() => {
    store = createStore(reducer, initialState)
  })

  describe('updateVersion', () => {
    it('has no timestamp originally', () => {
      expect(store.getState().lastUpdateVersionTimestamp).toBeUndefined()
    })
    it('sets the lastUpdateVersionTimestamp', () => {
      const time = new Date().getTime()
      store.dispatch(updateVersion())
      expect(store.getState().lastUpdateVersionTimestamp).toBeGreaterThanOrEqual(time)
    })
    it('sets allowed slippage and deadline', () => {
      store = createStore(reducer, {
        ...initialState,
        userDeadline: undefined,
        userSlippageTolerance: undefined
      } as any)
      store.dispatch(updateVersion())
      expect(store.getState().userDeadline).toEqual(DEFAULT_DEADLINE_FROM_NOW)
      expect(store.getState().userSlippageTolerance).toEqual(INITIAL_ALLOWED_SLIPPAGE)
    })
  })
})
Example #17
Source File: server.ts    From clearflask with Apache License 2.0 6 votes vote down vote up
// NOTE: If creating multiple projects, only one project can have projectId undefined
  // and is conside
  constructor(projectId?: string, settings?: StateSettings, apiOverride?: Client.ApiInterface & Admin.ApiInterface) {
    const projectStoreId = projectId || windowIso.location.hostname;
    const storeMiddleware = ServerAdmin.createStoreMiddleware(true, projectStoreId);
    if (windowIso.isSsr) {
      windowIso.storesState.serverStores = windowIso.storesState.serverStores || {};
      windowIso.storesState.serverStores[projectStoreId] = windowIso.storesState.serverStores[projectStoreId]
        || createStore(reducers, Server.initialState(projectId, settings), storeMiddleware);
      this.store = windowIso.storesState.serverStores[projectStoreId];
    } else {
      const preloadedState = (htmlDataRetrieve('__SSR_STORE_INITIAL_STATE__') as StoresStateSerializable | undefined)?.serverStores?.[projectStoreId]
        || Server.initialState(projectId, settings);
      this.store = createStore(reducers, preloadedState, storeMiddleware);
    }

    const apiConf: Client.ConfigurationParameters = {
      fetchApi: windowIso.fetch.bind(windowIso),
      basePath: Server.augmentApiBasePath(Client.BASE_PATH),
    };
    if (detectEnv() === Environment.DEVELOPMENT_FRONTEND) {
      apiOverride = ServerMock.get();
    }
    this.dispatcherClient = new Client.Dispatcher(
      msg => Server._dispatch(msg, this.store),
      new Client.Api(new Client.Configuration(apiConf), apiOverride));
    const adminStore = ServerAdmin.get().getStore();
    this.dispatcherAdmin = new Admin.Dispatcher(
      msg => Server._dispatch(msg, this.store, adminStore),
      new Admin.Api(new Admin.Configuration(apiConf), apiOverride));
  }
Example #18
Source File: store.ts    From extension with MIT License 6 votes vote down vote up
export function configureStore() {
  const store = createStore(
    createPersistReducer(extensionConfig),
    appInitialState,
    enhancer
  )
  const persistor = persistStore(store)
  return { store, persistor }
}
Example #19
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 #20
Source File: reducer.test.ts    From glide-frontend with GNU General Public License v3.0 6 votes vote down vote up
describe('application reducer', () => {
  let store: Store<ApplicationState>

  beforeEach(() => {
    store = createStore(reducer, {
      blockNumber: {
        [ChainId.MAINNET]: 3,
      },
    })
  })

  describe('updateBlockNumber', () => {
    it('updates block number', () => {
      store.dispatch(updateBlockNumber({ chainId: ChainId.MAINNET, blockNumber: 4 }))
      expect(store.getState().blockNumber[ChainId.MAINNET]).toEqual(4)
    })
    it('no op if late', () => {
      store.dispatch(updateBlockNumber({ chainId: ChainId.MAINNET, blockNumber: 2 }))
      expect(store.getState().blockNumber[ChainId.MAINNET]).toEqual(3)
    })
    it('works with non-set chains', () => {
      store.dispatch(updateBlockNumber({ chainId: ChainId.TESTNET, blockNumber: 2 }))
      expect(store.getState().blockNumber).toEqual({
        [ChainId.MAINNET]: 3,
        [ChainId.TESTNET]: 2,
      })
    })
  })
})
Example #21
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 #22
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 #23
Source File: App.tsx    From RNWCShop with GNU General Public License v3.0 6 votes vote down vote up
export default function App(): JSX.Element {
  return (
    <Provider store={createStore(cartReducer)}>
      <SafeAreaView style={{ flex: 1 }}>
        <NavigationContainer>
          <NavigationStacks />
        </NavigationContainer>
      </SafeAreaView>
    </Provider>
  );
}
Example #24
Source File: AppState.ts    From desktop-starter with MIT License 6 votes vote down vote up
constructor() {
    // this is the rootReducer for the application.
    this._rootReducer = combineReducers<RootState>({
      switchIModelState: AppReducer,
      frameworkState: FrameworkReducer,
    } as any);

    // create the Redux Store.
    this._store = createStore(this._rootReducer,
      (window as any).__REDUX_DEVTOOLS_EXTENSION__ && (window as any).__REDUX_DEVTOOLS_EXTENSION__());
  }
Example #25
Source File: store.ts    From polkabtc-ui with Apache License 2.0 6 votes vote down vote up
configureStore = (): StoreState => {
  const storeLogger = createLogger();
  const state = loadState();
  const store = createStore(rootReducer, state, applyMiddleware(storeLogger));
  store.dispatch(initializeState(state));
  store.subscribe(() => {
    saveState(store.getState());
  });
  return store;
}
Example #26
Source File: store.ts    From rn-clean-architecture-template with MIT License 6 votes vote down vote up
export function configureStore(): StoreContainer {
  const reducerManager = createReducerManager({
    authentication: authenticationReducer,
    configuration: configurationReducer,
  });
  const {rootEpic, epicMiddleware, epic$, addEpic} = createEpicManager(
    {},
    authenticationEpic,
    configurationEpic,
  );
  // Create a store with the root reducer function being the one exposed by the manager.

  const action$ = new BehaviorSubject<Action>({type: 'init'});
  const reducer = (
    state: RootStoreState | undefined,
    action: Action<string>,
  ) => {
    action$.next(action);
    return reducerManager.reduce(state, action);
  };
  const store = createStore<RootStoreState, Action<string>, any, any>(
    reducer,
    applyMiddleware(epicMiddleware),
  );
  epicMiddleware.run(rootEpic);

  // Optional: Put the reducer manager on the store so it is easily accessible
  return {
    reducerManager,
    store,
    epic$,
    action$,
    addEpic,
  };
}
Example #27
Source File: store.ts    From foodie with MIT License 6 votes vote down vote up
configureStore = () => {
    const store = createStore(
        rootReducer,
        reHydrateStore(),
        composeEnhancers(applyMiddleware(...middlewares)),
    );

    sagaMiddleware.run(rootSaga);
    return store;
}
Example #28
Source File: configureAppStore.ts    From bob-extension with MIT License 6 votes vote down vote up
export default function configureAppStore() {
  return createStore(
    rootReducer,
    process.env.NODE_ENV !== 'production'
      ? applyMiddleware(thunk, createLogger({
        collapsed: (getState, action = {}) => [''].includes(action.type),
      }))
      : applyMiddleware(thunk),
  );
}
Example #29
Source File: index.ts    From fe-v5 with Apache License 2.0 6 votes vote down vote up
start(): void {
    let reducer = this.getReducer();
    let sagas = this.getSagas();
    let sagaMiddleware = createSagaMiddleware();
    this.store = applyMiddleware(
      createPromiseMiddleware(this),
      sagaMiddleware,
    )(createStore)(reducer);
    sagas.forEach(sagaMiddleware.run);
  }