How to use @reduxjs/toolkit - 10 common examples

To help you get started, we’ve selected a few @reduxjs/toolkit examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github insideout10 / wordlift-plugin / src / src / js / src / mappings / reducers / mapping-list-reducers.js View on Github external
import { MAPPING_LIST_CHANGED, MAPPING_ITEM_CATEGORY_CHANGED, MAPPING_LIST_BULK_SELECT, MAPPING_LIST_CHOOSEN_CATEGORY_CHANGED, MAPPING_ITEM_SELECTED, BULK_ACTION_SELECTION_CHANGED, MAPPING_ITEMS_BULK_SELECT } from '../actions/action-types'
import { createReducer } from '@reduxjs/toolkit'
import { BulkOptionValues } from '../components/bulk-action-sub-components'
import { TRASH_CATEGORY, ACTIVE_CATEGORY } from '../components/category-component'

const changeCategoryForMappingItems = ( mapping_items, category ) => {
    return mapping_items.map( (item) => {
        item.mapping_status = category
        return item
    })
}

/**
  * Reducer to handle the mapping list section
  */
 export const MappingListReducer = createReducer(null, {
    [ MAPPING_LIST_CHANGED ] : ( state, action ) => {
        console.log( "state changed " )
        state.mapping_items = action.payload.value
    },
    [ MAPPING_ITEM_CATEGORY_CHANGED ] : ( state, action ) => {
        const { mappingId, mappingCategory } = action.payload
        const targetIndex = state.mapping_items
        .map( el => el.mapping_id )
        .indexOf( mappingId )
        state.mapping_items[ targetIndex ].mapping_status = mappingCategory
    },

    [ MAPPING_LIST_BULK_SELECT ] : ( state, action ) => {

        state.mapping_items = state.mapping_items.map((item) => {
            // Select only items in the current choosen category.
github berty / berty / js / packages / store / protocol / client.js View on Github external
unaryChan,
} from '../utils'
import ExternalTransport from './externalTransport'
import { getMainSettings } from '../settings/main'
import ProtocolServiceSagaClient from './ProtocolServiceSagaClient.gen'
import MessengerServiceSagaClient from '../messenger/MessengerServiceSagaClient.gen'
import { transactions as groupsTransactions, events as groupsEvents } from '../groups'

const protocolMethodsKeys = Object.keys(gen.Methods)
const messengerMethodsKeys = Object.keys(messengerGen.Methods)

const initialState = null

const commandsNames = [...Object.keys(gen.Methods), ...Object.keys(messengerGen.Methods), 'delete']

const commandsSlice = createSlice({
	name: 'protocol/client/command',
	initialState,
	// we don't change state on commands
	reducers: makeDefaultReducers(commandsNames),
})

const eventsNames = [
	...Object.keys(evgen.EventsNames),
	'started',
	'deleted',
	'contactRequestRdvSeedUpdated',
]

const eventHandler = createSlice({
	name: 'protocol/client/event',
	initialState,
github berty / berty / js / packages / store / messenger / account.js View on Github external
initialState,
	// this is stupid but getting https://github.com/kimamula/ts-transformer-keys in might be a headache
	// maybe move commands and events definitions in .protos
	reducers: makeDefaultReducers([
		'generate',
		'create',
		'delete',
		'sendContactRequest',
		'replay',
		'open',
		'onboard',
		'handleDeepLink',
	]),
})

const eventHandler = createSlice({
	name: 'messenger/account/event',
	initialState,
	reducers: {
		created: (state, { payload }) => {
			if (!state) {
				state = {
					name: payload.name,
					onboarded: false,
				}
			}
			return state
		},
		deleted: () => {
			return null
		},
		onboarded: (state) => {
github GridProtectionAlliance / openHistorian / Source / Applications / openHistorian / openHistorian / Grafana / public / app / features / datasources / state / reducers.ts View on Github external
export const initialState: DataSourcesState = {
  dataSources: [],
  plugins: [],
  categories: [],
  dataSource: {} as DataSourceSettings,
  layoutMode: LayoutModes.List,
  searchQuery: '',
  dataSourcesCount: 0,
  dataSourceTypeSearchQuery: '',
  hasFetched: false,
  isLoadingDataSources: false,
  dataSourceMeta: {} as DataSourcePluginMeta,
};

export const dataSourceLoaded = createAction('dataSources/dataSourceLoaded');
export const dataSourcesLoaded = createAction('dataSources/dataSourcesLoaded');
export const dataSourceMetaLoaded = createAction('dataSources/dataSourceMetaLoaded');
export const dataSourcePluginsLoad = createAction('dataSources/dataSourcePluginsLoad');
export const dataSourcePluginsLoaded = createAction(
  'dataSources/dataSourcePluginsLoaded'
);
export const setDataSourcesSearchQuery = createAction('dataSources/setDataSourcesSearchQuery');
export const setDataSourcesLayoutMode = createAction('dataSources/setDataSourcesLayoutMode');
export const setDataSourceTypeSearchQuery = createAction('dataSources/setDataSourceTypeSearchQuery');
export const setDataSourceName = createAction('dataSources/setDataSourceName');
export const setIsDefault = createAction('dataSources/setIsDefault');

// Redux Toolkit uses ImmerJs as part of their solution to ensure that state objects are not mutated.
// ImmerJs has an autoFreeze option that freezes objects from change which means this reducer can't be migrated to createSlice
// because the state would become frozen and during run time we would get errors because Angular would try to mutate
// the frozen state.
github GridProtectionAlliance / openHistorian / Source / Applications / openHistorian / openHistorian / Grafana / public / app / features / datasources / state / reducers.ts View on Github external
hasFetched: false,
  isLoadingDataSources: false,
  dataSourceMeta: {} as DataSourcePluginMeta,
};

export const dataSourceLoaded = createAction('dataSources/dataSourceLoaded');
export const dataSourcesLoaded = createAction('dataSources/dataSourcesLoaded');
export const dataSourceMetaLoaded = createAction('dataSources/dataSourceMetaLoaded');
export const dataSourcePluginsLoad = createAction('dataSources/dataSourcePluginsLoad');
export const dataSourcePluginsLoaded = createAction(
  'dataSources/dataSourcePluginsLoaded'
);
export const setDataSourcesSearchQuery = createAction('dataSources/setDataSourcesSearchQuery');
export const setDataSourcesLayoutMode = createAction('dataSources/setDataSourcesLayoutMode');
export const setDataSourceTypeSearchQuery = createAction('dataSources/setDataSourceTypeSearchQuery');
export const setDataSourceName = createAction('dataSources/setDataSourceName');
export const setIsDefault = createAction('dataSources/setIsDefault');

// Redux Toolkit uses ImmerJs as part of their solution to ensure that state objects are not mutated.
// ImmerJs has an autoFreeze option that freezes objects from change which means this reducer can't be migrated to createSlice
// because the state would become frozen and during run time we would get errors because Angular would try to mutate
// the frozen state.
// https://github.com/reduxjs/redux-toolkit/issues/242
export const dataSourcesReducer = (state: DataSourcesState = initialState, action: AnyAction): DataSourcesState => {
  if (dataSourcesLoaded.match(action)) {
    return {
      ...state,
      hasFetched: true,
      dataSources: action.payload,
      dataSourcesCount: action.payload.length,
    };
  }
github cockroachdb / cockroach-gen / pkg / ui / cluster-ui / src / store / liveness / liveness.selectors.ts View on Github external
// Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.

import { createSelector } from "@reduxjs/toolkit";
import { AppState } from "../reducers";

const livenessesSelector = (state: AppState) => state.adminUI.liveness.data;

export const livenessStatusByNodeIDSelector = createSelector(
  livenessesSelector,
  livenesses => livenesses?.statuses || {},
);
github pipe-cd / pipe / pkg / app / web / src / store.ts View on Github external
import { configureStore, getDefaultMiddleware } from "@reduxjs/toolkit";
import { thunkErrorHandler } from "./middlewares/thunk-error-handler";
import { reducers } from "./modules";

export const store = configureStore({
  reducer: reducers,
  devTools: process.env.NODE_ENV === "development",
  middleware: [
    ...getDefaultMiddleware({}),
    thunkErrorHandler,
    // @see https://redux-toolkit.js.org/usage/usage-with-typescript#correct-typings-for-the-dispatch-type
  ] as const,
});

export type AppState = ReturnType;
export type AppDispatch = typeof store.dispatch;
github codeforpdx / recordexpungPDX / src / frontend / src / redux / store.tsx View on Github external
// See the following guides for an explanation:
// https://redux-starter-kit.js.org/usage/usage-guide
// https://redux.js.org/recipes/usage-with-typescript
import { configureStore, getDefaultMiddleware } from "@reduxjs/toolkit";
import { combineReducers } from "redux";

// Reducers:
import { searchReducer } from "./search/reducer";

const rootReducer = combineReducers({
  search: searchReducer,
});

const store = configureStore({
  reducer: rootReducer,
  middleware: [...getDefaultMiddleware()],
});

export type AppState = ReturnType;

export default store;
github bunkerchat / bunker / src / store.js View on Github external
import { configureStore, getDefaultMiddleware } from "@reduxjs/toolkit";
import { createBrowserHistory } from "history";
import { connectRouter, routerMiddleware } from "connected-react-router";
import rootReducer from "./rootReducer";

const history = createBrowserHistory();

const middleware = getDefaultMiddleware({
	// TODO: a few reducers are not correctly immutable or serializable. Fix those and turn this back on
	// emoticonPicker is one
	immutableCheck: false,
	serializableCheck: false
});

const store = configureStore({
	reducer: connectRouter(history)(rootReducer),
	middleware: [routerMiddleware(history), ...middleware]
});

if (process.env.NODE_ENV === "development" && module.hot) {
	module.hot.accept("./rootReducer", () => {
		const newRootReducer = require("./rootReducer").default;
		store.replaceReducer(newRootReducer);
	});
github chaos-mesh / chaos-mesh / ui / src / store.ts View on Github external
import { AnyAction, configureStore, getDefaultMiddleware } from '@reduxjs/toolkit'
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'

import rootReducer from 'reducers'

const middlewares = getDefaultMiddleware({
  serializableCheck: false, // warn: in order to use the global ConfirmDialog, disable the serializableCheck check
})

const genStore = () => {
  if (process.env.NODE_ENV === 'development') {
    const { createLogger } = require('redux-logger')

    const logger = createLogger({
      predicate: (_: any, action: AnyAction) => {
        if (action.type.includes('pending')) {
          return false
        }

        return true
      },
    })