@reduxjs/toolkit#createSlice TypeScript Examples

The following examples show how to use @reduxjs/toolkit#createSlice. 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: backgroundSlice.ts    From overwolf-modern-react-boilerplate with MIT License 6 votes vote down vote up
backgroundWindowSlice = createSlice({
  name: 'backgroundWindow',
  initialState,
  reducers: {
    setEvent(state, action: PayloadAction<OverwolfEventPayload>) {
      const { event } = action.payload
      state.event = event
      state.events.push(event)
    },
    setInfo(state, action: PayloadAction<OverwolfInfoPayload>) {
      const { info } = action.payload
      state.info = info
      state.infos.push(info)
    },
  },
})
Example #2
Source File: ConfigSlice.ts    From bluebubbles-server with Apache License 2.0 6 votes vote down vote up
ConfigSlice = createSlice({
    name: 'config',
    initialState,
    reducers: {
        setConfig: (state, action: PayloadAction<ConfigItem>) => {
            if (action.payload.saveToDb ?? true) {
                ipcRenderer.invoke('set-config', { [action.payload.name]: action.payload.value });
            }

            if (state[action.payload.name] === action.payload.value) return;
            state[action.payload.name] = action.payload.value;
        },
        setConfigBulk: (state, action: PayloadAction<Array<ConfigItem>>) => {
            for (const i of action.payload) {
                // If the config already exists, we should send the update to the backend too.
                // If it's new, it's probably coming _from_ the server, so no need to set it
                if (i.saveToDb ?? true) {
                    ipcRenderer.invoke('set-config', { [i.name]: i.value });
                }

                if (state[i.name] === i.value) continue;
                state[i.name] = i.value;
            }
        }
    }
})
Example #3
Source File: slice.ts    From TutorBase with MIT License 6 votes vote down vote up
clientDataSlice = createSlice({
    name: "clientData",
    initialState,
    reducers: {
        setAppointment(state: ClientDataSlice, action: PayloadAction<Array<Appointment>>){
            state.appointments = action.payload;
        },
        clearAppointments(state: ClientDataSlice){
            state.appointments = [];
        },
        addAppointment(state: ClientDataSlice, action: PayloadAction<Appointment>){
            state.appointments.push(action.payload);
        },
        setFirstName(state: ClientDataSlice, action: PayloadAction<string>){
            state.first_name = action.payload;
        },
        setLastName(state: ClientDataSlice, action: PayloadAction<string>){
            state.last_name = action.payload;
        },
        setProfileImage(state: ClientDataSlice, action: PayloadAction<string>){
            state.profile_img = action.payload;
        },
        setIsTutor(state: ClientDataSlice, action: PayloadAction<boolean>){
            state.isTutor = action.payload;
        }
    },
})
Example #4
Source File: notificationSlice.ts    From react-tutorials with MIT License 6 votes vote down vote up
notifications = createSlice({
  name: 'notifications',
  initialState: {
    notification: {
      id: -1,
      type: '',
      description: '',
    },
  } as SliceState,
  reducers: {
    setNotification: (state, action) => {
      state.notification = {
        id: action.payload.id,
        type: action.payload.type,
        description: action.payload.description,
      }
    },
  },
})
Example #5
Source File: index.ts    From keycaplendar with MIT License 6 votes vote down vote up
auditSlice = createSlice({
  initialState,
  name: "audit",
  reducers: {
    setAllActions: (state, { payload }: PayloadAction<ActionType[]>) => {
      state.allActions = payload;
    },
    setFilterAction: (
      state,
      { payload }: PayloadAction<"created" | "deleted" | "none" | "updated">
    ) => {
      state.filterAction = payload;
    },
    setFilteredActions: (state, { payload }: PayloadAction<ActionType[]>) => {
      state.filteredActions = payload;
    },
    setFilterUser: (state, { payload }: PayloadAction<string>) => {
      state.filterUser = payload;
    },
    setLength: (state, { payload }: PayloadAction<number>) => {
      state.length = payload;
    },
    setLoading: (state, { payload }: PayloadAction<boolean>) => {
      state.loading = payload;
    },
    setUsers: (state, { payload }: PayloadAction<string[]>) => {
      state.users = payload;
    },
  },
})
Example #6
Source File: loader.ts    From frontend with GNU General Public License v3.0 6 votes vote down vote up
loader = createSlice({
  name: 'loader',
  initialState,
  reducers: {
    toggleLoader: (state): void => {
      state.isLoading = !state.isLoading;
    },
  },
})
Example #7
Source File: app-slice.ts    From lobis-frontend with MIT License 6 votes vote down vote up
appSlice = createSlice({
    name: "app",
    initialState,
    reducers: {
        fetchAppSuccess(state, action) {
            setAll(state, action.payload);
        },
    },
    extraReducers: builder => {
        builder
            .addCase(loadAppDetails.pending, (state, action) => {
                state.loading = true;
            })
            .addCase(loadAppDetails.fulfilled, (state, action) => {
                setAll(state, action.payload);
                state.loading = false;
            })
            .addCase(loadAppDetails.rejected, (state, { error }) => {
                state.loading = false;
                console.log(error);
            });
    },
})
Example #8
Source File: commonReducer.ts    From twitch-live-extension with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
commonSlice = createSlice({
    name: 'common',
    initialState: {
        loading: false,
    },
    reducers: {
        setLoading(state: CommonStore) {
            state.loading = !state.loading;
        },
    },
})
Example #9
Source File: app-slice.ts    From rugenerous-frontend with MIT License 6 votes vote down vote up
appSlice = createSlice({
  name: "app",
  initialState,
  reducers: {
    fetchAppSuccess(state, action) {
      setAll(state, action.payload);
    },
  },
  extraReducers: builder => {
    builder
      .addCase(loadAppDetails.pending, (state, action) => {
        state.loading = true;
      })
      .addCase(loadAppDetails.fulfilled, (state, action) => {
        setAll(state, action.payload);
        state.loading = false;
      })
      .addCase(loadAppDetails.rejected, (state, { error }) => {
        state.loading = false;
        console.log(error);
      });
  },
})
Example #10
Source File: notificationStateSlice.ts    From prism-frontend with MIT License 6 votes vote down vote up
notificationStateSlice = createSlice({
  name: 'notificationState',
  initialState,
  reducers: {
    addNotification: (
      { notifications, ...rest },
      { payload }: PayloadAction<NotificationConstructor>,
    ) => ({
      ...rest,
      notifications: notifications.concat(new Notification(payload)),
    }),
    removeNotification: (
      { notifications, ...rest },
      { payload }: PayloadAction<Notification['key']>,
    ) => ({
      ...rest,
      notifications: notifications.filter(
        notification => notification.key !== payload,
      ),
    }),
  },
})
Example #11
Source File: app-slice.ts    From wonderland-frontend with MIT License 6 votes vote down vote up
appSlice = createSlice({
    name: "app",
    initialState,
    reducers: {
        fetchAppSuccess(state, action) {
            setAll(state, action.payload);
        },
    },
    extraReducers: builder => {
        builder
            .addCase(loadAppDetails.pending, (state, action) => {
                state.loading = true;
            })
            .addCase(loadAppDetails.fulfilled, (state, action) => {
                setAll(state, action.payload);
                state.loading = false;
            })
            .addCase(loadAppDetails.rejected, (state, { error }) => {
                state.loading = false;
                console.log(error);
            });
    },
})
Example #12
Source File: slice.ts    From rewind with MIT License 6 votes vote down vote up
backendSlice = createSlice({
  name: "backend",
  initialState,
  reducers: {
    stateChanged(draft, action: PayloadAction<BackendState>) {
      draft.status = action.payload;
    },
  },
})
Example #13
Source File: blocks.ts    From frontend-v1 with GNU Affero General Public License v3.0 6 votes vote down vote up
blockSlice = createSlice({
  name: "block",
  initialState,
  reducers: {
    setBlock: (state, action) => {
      state.block = action.payload;
      return state;
    },
  },
  extraReducers: (builder) =>
    builder.addCase(toChain, (state) => {
      state = initialState;
      return state;
    }),
})
Example #14
Source File: App.slice.ts    From ts-redux-react-realworld-example-app with MIT License 6 votes vote down vote up
slice = createSlice({
  name: 'app',
  initialState,
  reducers: {
    initializeApp: () => initialState,
    loadUser: (state, { payload: user }: PayloadAction<User>) => {
      state.user = Some(user);
      state.loading = false;
    },
    logout: (state) => {
      state.user = None;
    },
    endLoad: (state) => {
      state.loading = false;
    },
  },
})
Example #15
Source File: collectionSlice.ts    From aqualink-app with MIT License 6 votes vote down vote up
collectionSlice = createSlice({
  name: "collection",
  initialState: collectionInitialState,
  reducers: {
    clearCollection: (state) => ({ ...state, details: undefined }),
    setName: (state, action: PayloadAction<string>) => ({
      ...state,
      details: state.details
        ? { ...state.details, name: action.payload }
        : state.details,
    }),
  },
  extraReducers: (builder) => {
    builder.addCase(
      collectionRequest.fulfilled,
      (state, action: PayloadAction<CollectionState["details"]>) => ({
        ...state,
        details: action.payload,
        loading: false,
      })
    );

    builder.addCase(
      collectionRequest.rejected,
      (state, action: PayloadAction<CollectionState["error"]>) => ({
        ...state,
        loading: false,
        error: action.payload,
      })
    );

    builder.addCase(collectionRequest.pending, (state) => ({
      ...state,
      loading: true,
      error: null,
    }));
  },
})
Example #16
Source File: slice.ts    From apps with MIT License 6 votes vote down vote up
battleSlice = createSlice({
    name: "battle",
    initialState,
    reducers: {
        queueAction: (state, action: PayloadAction<BattleQueuedAttack>) => {
            state.queuedAttacks.push(action.payload);
        },
        setActorSkills: (state, action: PayloadAction<BattleStateActorSkill[]>) => {
            state.actorSkills = action.payload;
        },
        setEvents: (state, action: PayloadAction<BattleEvent[]>) => {
            state.events = action.payload;
        },
        setEnemyActors: (state, action: PayloadAction<BattleStateActor[]>) => {
            state.enemyActors = action.payload;
        },
        setPlayerActors: (state, action: PayloadAction<BattleStateActor[]>) => {
            state.playerActors = action.payload;
        },
        startBattle: (state) => {
            state.running = true;
        },
        startPlayerAttacking: (state) => {
            state.playerActing = false;
            state.playerAttacking = true;
            state.playerTurn = true;
        },
        startPlayerTurn: (state) => {
            state.playerActing = true;
            state.playerAttacking = false;
            state.playerTurn = true;
        },
        stopPlayerAction: (state) => {
            state.playerActing = false;
            state.playerAttacking = false;
        },
    },
})
Example #17
Source File: counter.slice.ts    From react_js_clean_architecture with MIT License 6 votes vote down vote up
counterSlice = createSlice({
    name: "counter",
    initialState,
    reducers: {
        increment: (state) => ({
            ...state,
            value: state.value + 1,
        }),
        decrement: (state) => ({
            ...state,
            value: state.value === 0 ? 0 : state.value - 1,
        }),
        incrementByAmount: (state, action: PayloadAction<number>) => ({
            ...state,
            value: state.value + action.payload,
        }),
    },
})
Example #18
Source File: connections.ts    From camus with GNU Affero General Public License v3.0 6 votes vote down vote up
connectionsSlice = createSlice({
    name: 'connections',
    initialState,
    reducers: {
        addConnection(state, { payload }: PayloadAction<Connection>) {
            state.push(payload);
        },
        removeConnection(state, { payload }: PayloadAction<string>) {
            const id = payload;
            return state.filter((connection) => connection.id !== id);
        },
        updateConnection(state, { payload }: PayloadAction<{ id: string }>) {
            const { id } = payload;
            const connection = state.find((c) => c.id === id);
            Object.assign(connection, payload);
        },
    },
})
Example #19
Source File: balancesSlice.ts    From celo-web-wallet with MIT License 6 votes vote down vote up
balancesSlice = createSlice({
  name: 'balances',
  initialState: balancesInitialState,
  reducers: {
    updateBalances: (state, action: PayloadAction<Balances>) => {
      const { tokenAddrToValue, lockedCelo, lastUpdated } = action.payload
      assert(tokenAddrToValue && lockedCelo && lastUpdated, 'Invalid balance')
      state.accountBalances = action.payload
    },
    setVoterBalances: (state, action: PayloadAction<Balances | null>) => {
      state.voterBalances = action.payload
    },
    resetBalances: () => balancesInitialState,
  },
})
Example #20
Source File: tokenSlice.ts    From crypto-capsule with MIT License 6 votes vote down vote up
tokenSlice = createSlice({
  name: "tokens",
  initialState,
  reducers: {
    setTokens: (state, action: PayloadAction<Token[]>) => {
      state.tokens = action.payload;
    },
  },
})
Example #21
Source File: convert-dialog-feature.ts    From webminidisc with GNU General Public License v2.0 6 votes vote down vote up
slice = createSlice({
    name: 'convertDialog',
    initialState,
    reducers: {
        setVisible: (state, action: PayloadAction<boolean>) => {
            state.visible = action.payload;
        },
        setFormat: (state, action: PayloadAction<UploadFormat>) => {
            state.format = action.payload;
            savePreference('uploadFormat', state.format);
        },
        setTitleFormat: (state, action: PayloadAction<TitleFormatType>) => {
            state.titleFormat = action.payload;
            savePreference('trackTitleFormat', state.titleFormat);
        },
    },
})
Example #22
Source File: slice.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
ideSlice = createSlice({
  name: "ide",
  initialState: INITIAL_STATE,
  reducers: {
    setNoteActive: (state, action: PayloadAction<NoteProps | undefined>) => {
      state.notePrev = state.noteActive;
      state.noteActive = action.payload;
    },
    setTree: (state, action: PayloadAction<TreeMenu>) => {
      state.tree = action.payload;
    },
    setTheme: (state, action: PayloadAction<Theme>) => {
      state.theme = action.payload;
    },
    setGraphStyles: (state, action: PayloadAction<string>) => {
      state.graphStyles = action.payload;
    },
    setViewReady: (
      state,
      action: PayloadAction<{ key: DendronTreeViewKey; ready: boolean }>
    ) => {
      const { key, ready } = action.payload;
      state.views[key] = { ready };
    },
    refreshLookup: (
      state,
      action: PayloadAction<LookupModifierStatePayload>
    ) => {
      state.lookupModifiers = action.payload;
    },
    setSeedsInWorkspace: (state, action: PayloadAction<string[]>) => {
      state.seedsInWorkspace = action.payload;
    },
    setGraphTheme: (state, action: PayloadAction<GraphThemeEnum>) => {
      state.graphTheme = action.payload;
    },
  },
})
Example #23
Source File: downloadModule.ts    From baidu-pan-downloader with MIT License 6 votes vote down vote up
downloadModule = createSlice({
  name: 'download',
  initialState,
  reducers: {
    reset: (state) => {
      state = { ...initialState }
      return state
    },
    updateProgress: (state, action: PayloadAction<{ fsId: ItemProxy['fsId']; progress: Partial<IProgress> }>) => {
      const { fsId, progress } = action.payload
      const item = state.downloadItems[fsId]
      if (item) {
        state.downloadItems[fsId] = Object.assign(item, progress)
      }
      return state
    },
    change: (state, action: PayloadAction<Partial<State>>) => {
      const { payload } = action
      state = Object.assign(state, payload)
      return state
    },
    removeItem: (state, action: PayloadAction<{ fsId: ItemProxy['fsId'] }>) => {
      delete state.downloadItems[action.payload.fsId]
      return state
    },
    requestDownload: (state) => {
      state.processing += 1
      return state
    },
    successDownload: (state) => {
      state.processing -= 1
      return state
    },
    failureDownload: (state) => {
      state.processing -= 1
      return state
    },
  },
})
Example #24
Source File: appReducer.ts    From react-weather-app with GNU General Public License v3.0 6 votes vote down vote up
appSlice = createSlice({
  name: 'app',
  initialState,
  reducers: {
    toggleDarkMode: (state: IAppState) => {
      localStorage.setItem('darkMode', (!state.darkMode).toString());
      state.darkMode = !state.darkMode;
    },
    changeTempUnit: (state: IAppState) => {
      state.tempUnit = state.tempUnit === TempUnit.CELCIUS ? TempUnit.FAHRENHEIT : TempUnit.CELCIUS;
    },
    setIsLoading: (state: IAppState, action: PayloadAction<boolean>) => {
      state.isLoading = action.payload;
    },
    setIsInitial: (state: IAppState, action: PayloadAction<boolean>) => {
      state.isInitial = action.payload;
    },
  },
})
Example #25
Source File: reducer.ts    From frontegg-react with MIT License 6 votes vote down vote up
{ reducer, actions } = createSlice({
  name: 'root',
  initialState,
  reducers: {
    setContext: {
      prepare: (context: ContextOptions) => ({ payload: context }),
      reducer: (state: RootState, { payload }: PayloadAction<ContextOptions>) => ({
        ...state,
        context: payload,
      }),
    },
  },
})
Example #26
Source File: activeSiteID.ts    From local-addon-image-optimizer with MIT License 6 votes vote down vote up
activeSiteIDSlice = createSlice({
	name: 'activeSiteID',
	initialState: null,
	reducers: {
		setActiveSiteID: (state, action: PayloadAction<string>) => {
			state = action.payload;

			return state;
		},
	},
})
Example #27
Source File: index.ts    From glide-frontend with GNU General Public License v3.0 6 votes vote down vote up
achievementSlice = createSlice({
  name: 'achievements',
  initialState,
  reducers: {
    addAchievement: (state, action: PayloadAction<Achievement>) => {
      state.data.push(action.payload)
    },
    addAchievements: (state, action: PayloadAction<Achievement[]>) => {
      state.data = [...state.data, ...action.payload]
    },
    setAchievements: (state, action: PayloadAction<Achievement[]>) => {
      state.data = action.payload
    },
    clearAchievements: (state) => {
      state.data = []
    },
  },
})