@reduxjs/toolkit#PayloadAction TypeScript Examples

The following examples show how to use @reduxjs/toolkit#PayloadAction. 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: 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 #5
Source File: multiStepExample.ts    From frontend with GNU General Public License v3.0 6 votes vote down vote up
multiStepExample = createSlice({
  name: 'multiStepExample',
  initialState,
  reducers: {
    updateForm: (state, action: PayloadAction<{ [key: string]: string | boolean }>) => {
      return { ...state, ...action.payload };
    },
    clearForm: () => initialState,
  },
})
Example #6
Source File: messages-slice.ts    From lobis-frontend with MIT License 6 votes vote down vote up
messagesSlice = createSlice({
    name: "messages",
    initialState,
    reducers: {
        // Creates an error message
        error(state, action: PayloadAction<IMessage>) {
            createMessage(state, "error", action.payload);
        },
        // Creates an information message
        info(state, action: PayloadAction<IMessage>) {
            createMessage(state, "info", action.payload);
        },
        warning(state, action: PayloadAction<IMessage>) {
            createMessage(state, "warning", action.payload);
        },
        success(state, action: PayloadAction<IMessage>) {
            createMessage(state, "success", action.payload);
        },
        // Closes a message
        close(state) {
            state.message = null;
        },
    },
})
Example #7
Source File: twitchReducer.ts    From twitch-live-extension with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
twitchSlice = createSlice({
    name: 'twitch',
    initialState: {
        livestreams: [],
    } as TwitchStore,
    reducers: {
        saveLivestreams: (state: TwitchStore, { payload }: PayloadAction<FollowedLivestream[]>) => {
            state.livestreams = payload;
        },
        resetLivestreams: (state: TwitchStore) => {
            state.livestreams = [];
        },
    },
})
Example #8
Source File: messages-slice.ts    From rugenerous-frontend with MIT License 6 votes vote down vote up
messagesSlice = createSlice({
  name: "messages",
  initialState,
  reducers: {
    // Creates an error message
    error(state, action: PayloadAction<IMessage>) {
      createMessage(state, "error", action.payload);
    },
    // Creates an information message
    info(state, action: PayloadAction<IMessage>) {
      createMessage(state, "info", action.payload);
    },
    warning(state, action: PayloadAction<IMessage>) {
      createMessage(state, "warning", action.payload);
    },
    success(state, action: PayloadAction<IMessage>) {
      createMessage(state, "success", action.payload);
    },
    // Closes a message
    close(state) {
      state.message = null;
    },
  },
})
Example #9
Source File: EditorCategory.ts    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
emptyCategoryMiddleware: Middleware<unknown, AppState> = ({ dispatch, getState }) => (
  next
) => (action) => {
  switch (action.type) {
    case setTab.type:
      const currentState = getState();
      const setTabAction: PayloadAction<UIControlsTab> = action;
      switch (setTabAction.payload) {
        case 'features':
          handleSetTabFeatures(currentState, dispatch);

          // Pass on the original action without replacing or modifying it.
          break;
        case 'routes':
          handleSetTabRoutes(currentState, dispatch);

          // Pass on the action without replacing or modifying it.
          break;
      }
      break;
  }

  // Pass on the action without replacing or modifying it.
  return next(action);
}
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: pending-txns-slice.ts    From wonderland-frontend with MIT License 6 votes vote down vote up
pendingTxnsSlice = createSlice({
    name: "pendingTransactions",
    initialState,
    reducers: {
        fetchPendingTxns(state, action: PayloadAction<IPendingTxn>) {
            state.push(action.payload);
        },
        clearPendingTxn(state, action: PayloadAction<string>) {
            const target = state.find(x => x.txnHash === action.payload);
            if (target) {
                state.splice(state.indexOf(target), 1);
            }
        },
    },
})
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: connection.ts    From frontend-v1 with GNU Affero General Public License v3.0 6 votes vote down vote up
connectionSlice = createSlice({
  name: "connection",
  initialState,
  reducers: {
    update: (state, action: PayloadAction<Update>) => {
      const { account, chainId, provider, signer, name } = action.payload;
      state.account = account ? getAddress(account) : state.account;
      state.provider = provider ?? state.provider;
      // theres a potential problem with this: if onboard says a signer is undefined, we default them back
      // to the previous signer. This means we get out of sync with onboard and could have serious consequences.
      state.signer = signer ?? state.signer;
      state.name = name ?? state.name;
      if (chainId) {
        if (isSupportedChainId(chainId)) {
          state.chainId = chainId;
          if (state.error instanceof UnsupportedChainIdError) {
            state.error = undefined;
          }
        } else {
          state.error = new UnsupportedChainIdError(chainId);
        }
      }
      return state;
    },
    error: (state, action: PayloadAction<ErrorUpdate>) => {
      state.error = action.payload.error;
      return state;
    },
    disconnect: (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: index.ts    From camus with GNU Affero General Public License v3.0 6 votes vote down vote up
function* doSetUsername({ payload }: PayloadAction<string>) {
    const manager: Manager = yield getContext('manager');
    const username = payload;

    try {
        yield apply(manager, manager.setUsername, [username]);
        yield put({ type: 'MANAGER_UPDATED' });
    } catch (err) {
        yield put({ type: 'MANAGER_ERROR', payload: err });
    }
}
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 = []
    },
  },
})
Example #28
Source File: health-kit.ts    From nyxo-app with GNU General Public License v3.0 6 votes vote down vote up
healthKitSlice = createSlice({
  name: 'healthKitSlice',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    // Init
    builder.addCase(
      initHealthKit.fulfilled,
      (state, action: PayloadAction<boolean>) => {
        state.inited = action.payload
        state.loading = 'idle'
      }
    )
    builder.addCase(initHealthKit.pending, (state) => {
      state.loading = 'pending'
    })
    builder.addCase(initHealthKit.rejected, (state) => {
      state.inited = false
      state.loading = 'idle'
    })
    // Fetch
    builder.addCase(fetchHealthKit.fulfilled, (state) => {
      state.loading = 'idle'
    })
    builder.addCase(fetchHealthKit.pending, (state) => {
      state.loading = 'pending'
    })
    builder.addCase(fetchHealthKit.rejected, (state) => {
      state.loading = 'idle'
    })
  }
})