redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

RTK Query gets stuck pending and swallows errors thrown in addMatcher reducers

Open adamerose opened this issue 2 years ago • 22 comments

I just ran into this problem and found this comment saying it's expected behavior, but I'm making this issue with a clearer example for further discussion because this seems like a footgun that should be changed.

Below is an example with a login button. Click the button and it sends a POST request to the backend with credentials to log in and gets back user info + token, and stores them in the authSlice and displays the username.

https://codesandbox.io/p/github/adamerose/rtkq-reducer-error-example/master https://github.com/adamerose/rtkq-reducer-error-example

With the error thrown in the matchFulfilled reducer, the query gets stuck forever in this state even though the HTTP request completed successfully:

isUninitialized:false
isFetching:true
isSuccess:false
isError:false
const authSlice = createSlice({
  name: "auth",
  initialState: initialState,
  reducers: {
    logout: (state) => {
      state.user = null
    },
  },
  extraReducers: (builder) => {
    builder.addMatcher(
      api.endpoints.login.matchFulfilled,
      (state, { payload }) => {
        state.user = payload.user

        throw Error("Example error")
      },
    )
  },
})

It also seems to completely swallow the error and nothing appears in the console, which made it very hard to figure out why I was getting stuck pending in an actual project. I've included a separate Throw Error button that throws an error in a normal reducer and I can see it appear in the console, but for some reason the one inside the addMatcher example doesn't. Am I doing something wrong here?

image image image

adamerose avatar Oct 11 '23 21:10 adamerose