@reduxjs/toolkit#createReducer TypeScript Examples

The following examples show how to use @reduxjs/toolkit#createReducer. 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.ts    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
displayedReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(enqueueNotification, (state, action) => {
      state.notifications.push(action.payload);
    })
    .addCase(dismissNotification, (state, action) => {
      // Dismiss all notifications whose key matches the provided value.
      state.notifications = _.map(state.notifications, (notification) =>
        notification.options.key === action.payload
          ? { ...notification, dismissed: true }
          : notification
      );
    })
    .addCase(dismissAllNotifications, (state) => {
      // Dismiss all queued notifications.
      state.notifications = _.map(state.notifications, (notification) => ({
        ...notification,
        dismissed: true,
      }));
    })
    .addCase(removeNotification, (state, action) => {
      // Remove the notification from the state.
      // Called internally once the dismissal animation is complete.
      state.notifications = _.reject(
        state.notifications,
        (notification) => notification.options.key == action.payload
      );
    })
    .addCase(setPreferences, (state, action) => {
      return selectSlice(selectNamespace(action.payload)) ?? state;
    })
    .addCase(clearPreferences, () => {
      return initialState;
    });
})
Example #2
Source File: index.ts    From jellyfin-audio-player with MIT License 6 votes vote down vote up
settings = createReducer(initialState, {
    [setJellyfinCredentials.type]: (state, action) => ({
        ...state,
        jellyfin: action.payload,
    }),
    [setBitrate.type]: (state, action) => ({
        ...state,
        bitrate: action.payload,
    }),
    [setOnboardingStatus.type]: (state, action) => ({
        ...state,
        isOnboardingComplete: action.payload,
    }),
    [setReceivedErrorReportingAlert.type]: (state) => ({
        ...state,
        hasReceivedErrorReportingAlert: true,
    })
})
Example #3
Source File: authentication.reducer.ts    From rn-clean-architecture-template with MIT License 6 votes vote down vote up
authenticationReducer = createReducer(INITIAL_STATE, (builder) =>
  builder
    .addCase(signInBegin, (state) =>
      Object.assign(state, {isAuthenticating: true}),
    )
    .addCase(signInSuccess, (state) =>
      Object.assign(state, {isAuthenticating: false, isAuthorized: true}),
    )
    .addCase(signInFailed, (state) =>
      Object.assign(state, {isAuthenticating: false, isAuthorized: false}),
    )
    .addCase(signInLocally, (state) =>
      Object.assign(state, {
        isAuthenticatingLocally: true,
      }),
    )
    .addCase(signInLocallySuccess, (state) =>
      Object.assign(state, {
        isAuthenticatingLocally: false,
        isAuthorized: true,
      }),
    )
    .addCase(signInLocallyFailed, (state) =>
      Object.assign(state, {
        isAuthenticatingLocally: false,
        isAuthorized: false,
      }),
    ),
)
Example #4
Source File: reducers.ts    From xcloud-keyboard-mouse with GNU General Public License v3.0 6 votes vote down vote up
configDetailsReducer = createReducer<AllMyGamepadConfigs['configs']>(
  {
    [DEFAULT_CONFIG_NAME]: defaultGamepadConfig,
  },
  (builder) => {
    builder.addCase(fetchAllAction.fulfilled, (state, action) => {
      return action.payload.configs;
    });
    builder.addCase(deleteGamepadConfigAction.fulfilled, (state, action) => {
      delete state[action.payload.name];
    });
    builder.addCase(modifyGamepadConfigAction.fulfilled, (state, action) => {
      state[action.payload.name] = action.payload.gamepadConfig;
    });
  },
)
Example #5
Source File: reducers.ts    From xcloud-keyboard-mouse with GNU General Public License v3.0 6 votes vote down vote up
enabledReducer = createReducer<AllMyGamepadConfigs['isEnabled']>(true, (builder) => {
  builder.addCase(fetchAllAction.fulfilled, (state, action) => {
    return action.payload.isEnabled;
  });
  builder.addCase(activateGamepadConfigAction.fulfilled, () => {
    return true;
  });
  builder.addCase(disableGamepadConfigAction.fulfilled, () => {
    return false;
  });
})
Example #6
Source File: reducers.ts    From xcloud-keyboard-mouse with GNU General Public License v3.0 6 votes vote down vote up
activeConfigReducer = createReducer<AllMyGamepadConfigs['activeConfig']>(
  DEFAULT_CONFIG_NAME,
  (builder) => {
    builder.addCase(fetchAllAction.fulfilled, (state, action) => {
      return action.payload.activeConfig;
    });
    builder.addCase(activateGamepadConfigAction.fulfilled, (state, action) => {
      return action.payload.name;
    });
  },
)
Example #7
Source File: timeline.reducer.ts    From ace with GNU Affero General Public License v3.0 6 votes vote down vote up
timelineReducer = createReducer<{ activity: Activity[] }>({ activity: [] }, (builder) => {
    builder.addCase(logActivity, (state, action) => {
        state.activity.push(action.payload);

        if (state.activity.length > MAX_TIMELINE_SIZE) {
            state.activity.shift();
        }
    });
})
Example #8
Source File: simVarValues.reducer.ts    From ace with GNU Affero General Public License v3.0 6 votes vote down vote up
simVarValuesReducer = createReducer<SimVarValuesState>({}, (builder) => {
    builder.addCase(reset, (state) => {
        for (const key of Object.getOwnPropertyNames(state)) {
            delete state[key];
        }
    });

    builder.addCase(setSimVarValue, ((state, action) => {
        // TODO units
        const { prefix, name } = action.payload.variable;

        state[`${prefix}:${name}`] = action.payload.value;
    }));
})
Example #9
Source File: simVarElements.reducer.ts    From ace with GNU Affero General Public License v3.0 6 votes vote down vote up
simVarElementsReducer = createReducer<SimVarControl[]>([], (builder) => {
    builder.addCase(reset, (state) => {
        state.length = 0;
    });

    builder.addCase(loadControls, (state, action) => {
        for (const control of action.payload) {
            if (!state.some((it) => it.__uuid === control.__uuid)) {
                state.push(control);
            }
        }
    });

    builder.addCase(addControl, (state, action) => {
        const control = action.payload;

        if (!state.some((it) => it.__uuid === control.__uuid)) {
            state.push(control);
        }
    });

    builder.addCase(deleteControl, (state, action) => {
        const control = action.payload;

        return state.filter((it) => it.__uuid !== control.__uuid);
    });

    builder.addCase(editControl, (state, action) => {
        const control = state.find((el) => el.__uuid === action.payload.__uuid);

        for (const key in control) {
            if (key in action.payload && key !== '__uuid') {
                (control as any)[key] = (action.payload as any)[key];
            }
        }
    });
})
Example #10
Source File: persistentStorage.reducer.ts    From ace with GNU Affero General Public License v3.0 6 votes vote down vote up
persistentStorageReducer = createReducer<Record<string, string>>({}, (builder) => {
    builder.addCase(reset, (state) => {
        for (const key of Object.getOwnPropertyNames(state)) {
            delete state[key];
        }
    });

    builder.addCase(setPersistentValue, ((state, action) => {
        const [key, value] = action.payload;

        state[key] = value;
    }));

    builder.addCase(deletePersistentValue, (state, action) => {
        delete state[action.payload];
    });
})
Example #11
Source File: coherent.reducer.ts    From ace with GNU Affero General Public License v3.0 6 votes vote down vote up
coherentReducer = createReducer<{ events: { data: CoherentEventData, clear:() => void }[] }>({ events: [] }, (builder) => {
    builder.addCase(reset, (state) => {
        state.events.length = 0;
    });

    builder.addCase(addCoherentEvent, (state, action) => {
        state.events.push(action.payload);
    });

    builder.addCase(clearCoherentEvent, (state, action) => {
        state.events.splice(state.events.findIndex((event) => event.data.uuid === action.payload), 1);
    });

    builder.addCase(clearCoherentEventsForUniqueID, (state, action) => {
        state.events = state.events.filter((it) => it.data.instrumentUniqueId !== action.payload);
    });
})
Example #12
Source File: Reducer.ts    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
i18nReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(setLanguage, (state, action) => {
      state.currentLanguage = action.payload;
    })
    .addCase(setPreferences, (state, action) => {
      return selectSlice(selectNamespace(action.payload)) ?? state;
    })
    .addCase(clearPreferences, () => {
      return initialState;
    });
})
Example #13
Source File: Reducer.ts    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
optionsReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(setCompletedAlpha, (state, action) => {
      state.completedAlpha = action.payload;
    })
    .addCase(setClusterMarkers, (state, action) => {
      state.clusterMarkers = action.payload;
    })
    .addCase(setWorldBorderEnabled, (state, action) => {
      state.worldBorderEnabled = action.payload;
    })
    .addCase(setRegionLabelsEnabled, (state, action) => {
      state.regionLabelsEnabled = action.payload;
    })
    .addCase(setHideFeaturesInEditor, (state, action) => {
      state.hideFeaturesInEditor = action.payload;
    })
    .addCase(setHideRoutesInEditor, (state, action) => {
      state.hideRoutesInEditor = action.payload;
    })
    .addCase(setShowHiddenFeaturesInSummary, (state, action) => {
      state.showHiddenFeaturesInSummary = action.payload;
    })
    .addCase(setOverrideLang, (state, action) => {
      state.overrideLang = action.payload;
    })
    .addCase(setPreferences, (state, action) => {
      return selectSlice(selectNamespace(action.payload)) ?? state;
    })
    .addCase(clearPreferences, () => {
      return initialState;
    });
})
Example #14
Source File: Reducer.ts    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
loadingReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(disableGoogleAuth, (state) => {
      state.google.enabled = false;
    })
    .addCase(setGoogleAuthProfile, (state, action) => {
      state.google.profile = action.payload;
    })
    .addCase(initializeGoogleClient, (state) => {
      state.google.initialized = true;
    })
    .addCase(setGoogleClientInProgress, (state, action) => {
      state.google.inProgress = action.payload;
    })
    .addCase(setPreferences, (state, action) => {
      return selectSlice(selectNamespace(action.payload)) ?? state;
    })
    .addCase(clearPreferences, () => {
      return initialState;
    });
})
Example #15
Source File: Reducer.ts    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
loadingReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(setLoading, (state, action) => {
      state[action.payload.loadingKey] = action.payload.newValue;
    })
    .addCase(setPreferences, (state, action) => {
      return selectSlice(selectNamespace(action.payload)) ?? state;
    })
    .addCase(clearPreferences, () => {
      return initialState;
    });
})
Example #16
Source File: Reducer.ts    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
displayedReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(setImportError, (state, action) => {
      state.importError = action.payload;
    })
    .addCase(clearImportError, (state) => {
      state.importError = initialState.importError;
    })
    .addCase(clearErrors, () => {
      return initialState;
    })
    .addCase(setPreferences, (state, action) => {
      return selectSlice(selectNamespace(action.payload)) ?? state;
    })
    .addCase(clearPreferences, () => {
      return initialState;
    });
})
Example #17
Source File: canvas.reducer.ts    From ace with GNU Affero General Public License v3.0 6 votes vote down vote up
canvasReducer = createReducer<CanvasState>({ elements: [] }, (builder) => {
    builder.addCase(reset, (state) => {
        state.elements.length = 0;
    });

    builder.addCase(loadCanvasElements, (state, action) => {
        state.elements = [...action.payload];

        for (const element of state.elements) {
            if (element.__kind === 'instrument' && !element.dataKind) {
                element.dataKind = ('url' in element) ? 'web' : 'bundled';
            }
        }
    });

    builder.addCase(addCanvasElement, (state, action) => {
        if (state.elements.some((it) => it.__uuid === action.payload.__uuid)) {
            throw new Error('Cannot add element with existing UUID');
        }

        state.elements.push(action.payload);
    });

    builder.addCase(updateCanvasElement, (state, action) => {
        const editElement = state.elements.find((it) => it.__uuid === action.payload.__uuid);

        for (const key of Object.keys(action.payload)) {
            (editElement as any)[key] = (action.payload as any)[key];
        }
    });

    builder.addCase(removeCanvasElement, (state, action) => {
        state.elements = state.elements.filter((it) => it.__uuid !== action.payload);
    });
})
Example #18
Source File: Reducer.ts    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
completedReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(setMarkerCompleted, (state, action) => {
      setRecord(state.features, action.payload.key, action.payload.timestamp);
    })
    .addCase(setMarkersCompleted, (state, action) => {
      for (const key in action.payload.keys) {
        setRecord(state.features, key, action.payload.timestamp);
      }
    })
    .addCase(clearMarkerCompleted, (state, action) => {
      deleteRecord(state.features, action.payload);
    })
    .addCase(clearMarkersCompleted, (state, action) => {
      state.features = _.pickBy(state.features, (_value, key) => !_.includes(action.payload, key));
    })
    .addCase(clearFeatureCompleted, (state, action) => {
      state.features = _.pickBy(state.features, (_value, key) => _.startsWith(key, action.payload));
    })
    .addCase(setPreferences, (state, action) => {
      return selectSlice(selectNamespace(action.payload)) ?? state;
    })
    .addCase(clearPreferences, () => {
      return initialState;
    });
})
Example #19
Source File: Reducer.ts    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
displayedReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(setFeatureDisplayed, (state, action) => {
      setRecord(state.features, action.payload, true);
    })
    .addCase(clearFeatureDisplayed, (state, action) => {
      setRecord(state.features, action.payload, false);
    })
    .addCase(toggleFeatureDisplayed, (state, action) => {
      setRecord(
        state.features,
        action.payload,
        !(getRecord(state.features, action.payload) ?? false)
      );
    })
    .addCase(setRouteGroupDisplayed, (state, action) => {
      setRecord(state.routes, action.payload, true);
    })
    .addCase(clearRouteGroupDisplayed, (state, action) => {
      setRecord(state.routes, action.payload, false);
    })
    .addCase(toggleRouteGroupDisplayed, (state, action) => {
      setRecord(state.routes, action.payload, !(getRecord(state.routes, action.payload) ?? false));
    })
    .addCase(setPreferences, (state, action) => {
      return selectSlice(selectNamespace(action.payload)) ?? state;
    })
    .addCase(clearPreferences, () => {
      return initialState;
    });
})
Example #20
Source File: notifications.reducer.ts    From ace with GNU Affero General Public License v3.0 5 votes vote down vote up
notificationsReducer = createReducer([], (builder) => {
    builder.addCase(pushNotification, (state, action) => {
        state.push(action.payload);
    });
    builder.addCase(popNotification, (state) => {
        state.shift();
    });
})
Example #21
Source File: counter-reducer.ts    From Riakuto-StartingReact-ja3.1 with Apache License 2.0 5 votes vote down vote up
counterReducer = createReducer(initialState, {
  [added.type]: (state, action: PayloadAction<number>) => ({
    ...state,
    count: action.payload,
  }),
  [decremented.type]: (state) => ({ ...state, count: state.count - 1 }),
  [incremented.type]: (state) => ({ ...state, count: state.count + 1 }),
})
Example #22
Source File: configuration.reducer.ts    From rn-clean-architecture-template with MIT License 5 votes vote down vote up
configurationReducer = createReducer(INITIAL_STATE, (builder) =>
  builder.addCase(setTheme, (state, {payload: themeConfig}) =>
    Object.assign(state, {themeConfig}),
  ),
)
Example #23
Source File: reducers.ts    From xcloud-keyboard-mouse with GNU General Public License v3.0 5 votes vote down vote up
pendingStatusesReducer = createReducer<PendingStatusesState>(
  {
    readAll: 'idle',
    gameStatus: 'idle',
    configs: {},
  },
  (builder) => {
    builder.addCase(fetchAllAction.pending, (state) => {
      state.readAll = 'reading';
    });
    builder.addCase(fetchAllAction.fulfilled, (state) => {
      state.readAll = 'success';
    });
    builder.addCase(fetchAllAction.rejected, (state, action) => {
      state.readAll = 'failure';
      state.readAllError = action.error;
    });
    builder.addCase(fetchGameStatusAction.pending, (state) => {
      state.gameStatus = 'reading';
    });
    builder.addCase(fetchGameStatusAction.fulfilled, (state) => {
      state.gameStatus = 'success';
    });
    builder.addCase(fetchGameStatusAction.rejected, (state) => {
      state.gameStatus = 'failure';
    });
    builder.addMatcher(
      (action) => isWriteAction(action) && isPending(action),
      (state, action) => {
        state.configs[action.meta.arg.name] = 'writing';
      },
    );
    builder.addMatcher(
      (action) => isWriteAction(action) && isFulfilled(action),
      (state, action) => {
        state.configs[action.payload.name] = 'success';
      },
    );
    builder.addMatcher(
      (action) => isWriteAction(action) && isRejected(action),
      (state, action) => {
        if (action.payload) {
          state.configs[action.payload.name] = 'failure';
        }
      },
    );
  },
)
Example #24
Source File: Reducer.ts    From Teyvat.moe with GNU General Public License v3.0 5 votes vote down vote up
displayedReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(setFeatureName, (state, action) => {
      state.feature.name = action.payload;
    })
    .addCase(setFeatureCategory, (state, action) => {
      state.feature.category = action.payload;
    })
    .addCase(setFeatureRegion, (state, action) => {
      state.feature.region = action.payload;
    })
    .addCase(clearElements, (state) => {
      state.feature.data = [];
    })
    .addCase(replaceMarker, (state, action) => {
      state.feature.data = _.map(state.feature.data, (marker) =>
        marker.id === action.payload.existingId ? action.payload.newMarker : marker
      );
    })
    .addCase(replaceRoute, (state, action) => {
      state.feature.data = _.map(state.feature.data, (route) =>
        route.id === action.payload.existingId ? action.payload.newRoute : route
      );
    })
    .addCase(removeMarker, (state, action) => {
      state.feature.data = _.reject(state.feature.data, (element) => element.id == action.payload);
    })
    .addCase(removeRoute, (state, action) => {
      state.feature.data = _.reject(state.feature.data, (element) => element.id == action.payload);
    })
    .addCase(appendMarker, (state, action) => {
      state.feature.data.push(action.payload);
    })
    .addCase(appendRoute, (state, action) => {
      state.feature.data.push(action.payload);
    })
    .addCase(editMarker, (state, action) => {
      _.forEach(_.filter(state.feature.data, ['id', action.payload.existingId]), (marker) => {
        _.set(marker, action.payload.markerProperty, action.payload.propertyValue);
      });
    })
    .addCase(editRoute, (state, action) => {
      _.forEach(_.filter(state.feature.data, ['id', action.payload.existingId]), (route) => {
        _.set(route, action.payload.routeProperty, action.payload.propertyValue);
      });
    })
    .addCase(setPreferences, (state, action) => {
      return selectSlice(selectNamespace(action.payload)) ?? state;
    })
    .addCase(clearPreferences, () => {
      return initialState;
    });
})
Example #25
Source File: reducers.ts    From xcloud-keyboard-mouse with GNU General Public License v3.0 5 votes vote down vote up
currentGameReducer = createReducer<string | null>(null, (builder) => {
  builder.addCase(fetchGameStatusAction.fulfilled, (state, action) => action.payload || null);
})
Example #26
Source File: Reducer.ts    From Teyvat.moe with GNU General Public License v3.0 5 votes vote down vote up
displayedReducer = createReducer(initialState, (builder) => {
  builder
    .addCase(setTab, (state, action) => {
      state.tab = action.payload;
    })
    .addCase(setMapCategory, (state, action) => {
      state.mapCategory = action.payload;
    })
    .addCase(setMapRegion, (state, action) => {
      state.mapRegion = action.payload;
    })
    .addCase(setOpen, (state, action) => {
      state.open = action.payload;
    })
    .addCase(toggleOpen, (state) => {
      state.open = !state.open;
    })
    .addCase(setMapHighlight, (state, action) => {
      state.mapHighlight = action.payload;
    })
    .addCase(clearMapHighlight, (state) => {
      state.mapHighlight = null;
    })
    .addCase(setMapPosition, (state, action) => {
      state.mapPosition = action.payload;
    })
    .addCase(setEditorEnabled, (state, action) => {
      state.editorEnabled = action.payload;
    })
    .addCase(toggleEditorEnabled, (state) => {
      state.editorEnabled = !state.editorEnabled;
    })
    .addCase(setEditorDebugEnabled, (state, action) => {
      state.editorDebugEnabled = action.payload;
    })
    .addCase(toggleEditorDebugEnabled, (state) => {
      state.editorDebugEnabled = !state.editorEnabled;
    })
    .addCase(setMapMarkerCount, (state, action) => {
      state.mapStats.markerCount = action.payload;
    })
    .addCase(setMapRouteCount, (state, action) => {
      state.mapStats.routeCount = action.payload;
    })
    .addCase(setPermalinkId, (state, action) => {
      state.permalinkId = action.payload;
    })
    .addCase(setPreferences, (state, action) => {
      return selectSlice(selectNamespace(action.payload)) ?? state;
    })
    .addCase(clearPreferences, () => {
      return initialState;
    });
})
Example #27
Source File: projectData.reducer.ts    From ace with GNU Affero General Public License v3.0 5 votes vote down vote up
projectDataReducer = createReducer<{ data: ProjectData | null }>({ data: null }, (builder) => {
    builder.addCase(setProjectData, (state, action) => {
        state.data = action.payload;
    });
})
Example #28
Source File: interactionToolbar.reducer.ts    From ace with GNU Affero General Public License v3.0 5 votes vote down vote up
interactionToolbarReducer = createReducer<{ panel: WorkspacePanelSelection }>({ panel: WorkspacePanelSelection.None }, (builder) => {
    builder.addCase(selectWorkspacePanel, (state, action) => {
        state.panel = action.payload;
    });
})
Example #29
Source File: interaction.reducer.ts    From ace with GNU Affero General Public License v3.0 5 votes vote down vote up
interactionReducer = createReducer<{ inInteractionMode: boolean }>({ inInteractionMode: false }, (builder) => {
    builder.addCase(setInteractionMode, (state, action) => {
        state.inInteractionMode = action.payload;
    });
})