I'm looking to streamline my code by creating shared functionality across multiple reducers with the help of create

Previously, in the older way of using Redux, we could create a reducer like this - handling different action types but with the same action:

export default function authReducer(state = initialState, action) {
  switch (action.type) {
    case AUTH_ERROR:
    case LOGIN_FAIL:
    case LOGOUT_SUCCESS:
    case REGISTER_FAIL:
      localStorage.removeItem("xts0");
      return {
        ...state,
        token: null,
        user: null,
        isAuthenticated: false,
        isLoading: false,
      };
    default:
      return state;
  }
}

Now, how can I achieve the same functionality using the createSlice utility?

const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    authError(state, action){},
    loginFail(state, action){},
    and so on
  }
})

Answer №1

To simplify the state update logic, you can create a single reducer function.

const resetAuth = (state, action) => {
  localStorage.removeItem("xts0");
  return initialState;
};

If actions from the `authSlice` require the same state update logic, you can use the `resetAuth` reducer function for each action:

const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    authError: resetAuth,
    loginFail: resetAuth,
    // ... and so on
  },
});

If these actions already exist and need to be handled by the `authSlice`, utilize the `extraReducers` property to define additional reducer cases for external actions:

const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    ...
  },
  extraReducers: builder => {
    builder
      .addCase(authError, resetAuth)
      .addCase(loginFail, resetAuth)
      // ... and so on
  },
});

In the scenario where the actions are not Redux-Toolkit actions but legacy Redux actions, specify the `type` property in the case declaration, e.g.,

.addCase(authError.type, resetAuth)
.

For code optimization, consider using a Matcher to reduce redundancy and boilerplate code:

import { isAnyOf } from '@reduxjs/toolkit';

const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    ...
  },
  extraReducers: builder => {
    builder
      .addMatcher(isAnyOf(authError, loginFail, /* ... and so on */), resetAuth);
  },
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The simultaneous use of trackball controls and GUI is not compatible

When I click on them, the GUI changes together and I have looked at other answers. However, I am not sure where to put the listener. I tried putting the listener in render(), but it still doesn't work. How can I fix my code? This coding is related to ...

Ensuring a correct dismount of a React component

Apologies for the lack of specificity in the title of this inquiry. Upon executing the code snippet below, I encountered the ensuing warning: Warning: setState(...): Can only update a mounted or mounting component. This typically indicates that you call ...

Retrieve the chosen item along with its quantity

I'm currently working on building a shopping cart application similar to this example using React.js. index.js: (Sending each product to the product component) {products.length > 0 ? products.map((product) => ( <Produ ...

Error in Typescript syntax within a CommonJS/Node module: Unexpected colon token found in function parameter

After validating the file with TS, there are no more errors. However, during runtime, I encounter an "Unexpected token ':'" error on any of the specified TS, such as immediately erroring on function (err: string). The following are my build and ...

Determining if a component is nested within itself in Angular 6 is a crucial task

My goal is to develop a custom Angular component for a nested navigation menu with multiple levels. Below is an example of how the menu structure looks: app.component.html <nav-menu> <nav-menu-item>Section 1</nav-menu-item> <nav- ...

An Overview of Implementing Ajax Calls for Partial Views on Form Submission

Check out my jQuery code below: <script type="text/javascript"> $("#submitfileform").submit(function () { $.ajax({ type: 'POST', contentType: 'application/html;charset=utf-8', dataT ...

Struggling to perform a basic http GET request in Angular 2

Attempting to create a basic http GET request in my Angular2 app: this.http.get("https://mybaseurl.com/hello") .map(res => res.json()) .subscribe( function(response) { console.log("Success Response" + response)}, function(error) { conso ...

The ngModel directive automatically clears the checkbox's Checked status

Currently, my Angular code is set up to validate a checkbox using ng-model: <input type="checkbox" name="news1" value="news1" ng-model="news" <c:if test="${xxxx == yes'}">checked="checked"></c:if>> <label ng-click="news1();"&g ...

Sending information from a Vuex module to a component following an axios request

I'm currently working on developing a Vue.js based application. Here's the scenario I'm facing: I have a component with a popup where users can create an 'expense' entry. Upon clicking the 'save' button, a function in the ...

Tips for enforcing validation rules at the class level using Angular's version of jQuery Validate

After utilizing jQuery Validate's convenient addClassRules function to impose a rule on all elements of a specific class, rather than relying on the attributes of their name, I encountered a roadblock when trying to do the same with the Angular wrappe ...

By implementing Async.parallel, I ensure that the lifetime of my parameter does not exceed the duration of the asynchronous calls in NodeJS when working with MongoDB

After analyzing the code and its asynchronous behavior, it appears that the 'recipeData' array may not persist long enough to handle the asynchronous callbacks. To mitigate this, I created a copy of the data in a global array. However, I am encou ...

Encountering difficulty in assigning the desired value to the select box

// updating the subType value in the controller $scope.newEngagement.subType = 3; // creating a list of engagement subTypes $scope.engagementSubTypeList = [ { "subTypeId": 1, "subTypeName": "value1" }, { "subTypeId": 2, "subTypeName": "value2" }, { " ...

Clicking on the parent page prevents the hyperlink inside the iframe from working as expected

I am having an issue with a hyperlink inside an iframe. When I click on it in the parent page, it doesn't work. Here is how it is set up: iframe.html <h1>I'm inner page!</h1> <a id="shared" class="btn" href=&q ...

"What is the best approach for setting up an Azure Web App to host both an Express static site and API

Setting up an Express app was a breeze for me, but when it comes to deploying it on Azure Web App, I'm hitting some roadblocks! The structure of my app is quite simple: a static web app with its own API. Requests to /website.com/api are forwarded to ...

What steps can be taken to ensure that the v-model input is not updated?

Typically, when a user enters a value in an input field, it automatically updates a model. However, I am looking to temporarily prevent this automatic update. In my application, I have a canvas where users can draw grids by entering lengths and widths in i ...

What could be causing my node server's REST endpoints to not function properly?

Here is a snippet of my index.js file: var http = require('http'); var express = require('express'); var path = require('path'); var bodyParser = require('body-parser') var app = express(); var currentVideo = &apos ...

Why is there a CSS reference failure in Express and how can it be resolved?

Below, you'll find a simple express server I've put together: // check out my basic Express server var express = require("express"); var app = express(); var bodyparser = require("body-parser"); app.use("/public/", express.static("./public/")); ...

What is the optimal frequency for saving data when dealing with a particularly extensive form?

I am facing a challenge with saving data to the database using Ajax. While I can handle this aspect, my difficulty lies in the fact that I have a very extensive form that is nested and cannot be altered. This large form consists of approximately 100 input ...

Is it possible to send multiple HTML input values to a Google Spreadsheet using only JavaScript?

Seeking a faster and more efficient way to send the values of multiple HTML Inputs to a specific location in a Google Spreadsheet? The existing script takes too long to complete, often skips inputs, and relies heavily on "google.script.run". Due to softwar ...

Change the value of the material slide toggle according to the user's response to the JavaScript 'confirm' dialogue

I am currently working on implementing an Angular Material Slide Toggle feature. I want to display a confirmation message if the user tries to switch the toggle from true to false, ensuring they really intend to do this. If the user chooses to cancel, I&ap ...