Search code examples
javascriptreactjsreduxredux-toolkitrtk-query

RTK query stuck at 'loading' state


I've a RTK query which returns user information from backend after loggin in. I've also created a slice reducer which takes the payload of RTK query(login call from backend) and stores user information, token in a state(redux-toolkit). Everything works fine untill I update the state using ExtraReducers. The RTK query gets Stuck at 'loading' state if I include state.token= payload.token , on removing the line, everything works fine(I can access the payload by selecting the 'user' Reducer). I want user token to be stored in user slice so that I can access it in headers and send it back to backend. Can anybody explain why this is happening?

import { createSlice } from "@reduxjs/toolkit";
import authService from "../Services/authService";

const initialState = {
  token: null,
};

const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    userLogin: (state, action) => {
    },
  },
  extraReducers: (builder) => {
    builder.addMatcher(
      authService.endpoints.authLogin.matchFulfilled,
      (state, { payload }) => {
        localStorage.setItem("userToken", payload.token);
        state.token = payload.token;
        return payload;
      }
    );
  },
});

export const { userLogin } = userSlice.actions;

export default userSlice.reducer;


Solution

  • It is very likely that you have an error message on your console that your are ignoring.

    In RTK Reducers (or any immerized function in general), you can either return a new value, or modify state. Doing both at once doesn't make any sense.

    So you probably want to skip the return statement and do

    
        builder.addMatcher(
          authService.endpoints.authLogin.matchFulfilled,
          (state, { payload }) => {
            localStorage.setItem("userToken", payload.token);
            state.token = payload.token;
          }