0

so I have auth reducer and loading reducer. I'd like to set the state in loading reducer whenever the createAsynchThunk in auth reducer is pending. the code look like this:

//auth reducer
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import {callPOSTSignInUserAccount} from "api"

export const signInRequest = createAsyncThunk(
  "auth/login",
  async (userData: UserDataLogin, thunkAPI) => {
    try {
      const result = await callPOSTSignInUserAccount(
        userData.email,
        userData.password
      );

      const auth = result.data.AuthenticationResult;
      const user = result.data.user;
     catch(err) {
      const result = {
                  alert: {
                    type: "error",
                    message: errMsg
                  }
                }
       return thunkAPI.rejectWithValue(result)
     }
  }
  
  //state
  const authState = {
    isAuthenticated = true,
    errorSignIn = "",
    auth: {},
  };
  
  //slice for auth
  const sliceAuth = createSlice({
  name: "auth",
  initialState: authState,
  reducers: {}, 
  extraReducers: (builder) => {
    //Sign in request
      .addCase(signInRequest.pending, (state, action) => {
       //set loading reducer state from here
      })
      .addCase(signInRequest.fulfilled, (state, action:any) => {
        if (action.payload?.auth !== undefined) {
          state.isAuthenticated = true
          state.errorSignIn = ""
          state.auth = action.payload.auth
        }
      })
      .addCase(signInRequest.rejected, (state, action:any) => {
        //also set alert here
      })
  }
  
  const authReducer = sliceAuth.reducer
  
  export default authReducer

//loading reducer

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

const loadingState = {
    appLoading: false,
};

const sliceLoading = createSlice({
  name: "loading",
  initialState: loadingState,
  reducers: {
    setLoading: (state, action) => {
    state.apploading = action.payload
  }
})

const reducerLoading = sliceLoading.reducer

export default reducerLoading

from what I read I can't dispatch an action in reducer because it's anti-pattern. I want to change the loading state in loading reducer from the auth reducer. I can add loading in the auth reducer initial state but it become hard to manage whenever I have more than one reducer in a react component.

dewey
  • 1
  • Why you need to create a separate reducer for loading? You can add a state in auth reducer and set the state to loading when the request is in pending and once request is fulfilled, revert the loading state. – Nouman Rafique Apr 26 '22 at 21:33

0 Answers0