Why data in successful mutation request is possibly undefined in Redux Toolkit Query

54 views Asked by At

In if statement, when request successful, data has type const data: IAuthResponse | undefined. Why is that so?

const [login, { data, isSuccess }] = useLoginMutation()
  const onSubmit = (loginData: ILoginData) => {
    login(loginData)
  }
  if (isSuccess) {
      localStorage.setItem('token', data.accessToken)
    }

Here definition of endpoint:

login: builder.mutation<IAuthResponse, ILoginData>({
        query: ({ email, password }) => ({ url: '/login', method: "POST", body: { email, password } }),
        invalidatesTags: ['Auth'],
      }),

since isSucces indicates that the last mutation fired has data from a successful request, so I expect that data would not be undefined

1

There are 1 answers

0
Yaroslav Maksymenko On

I found the way to avoid this problem by using onQueryStarted and generally it seems to be better approach:

login: builder.mutation<IAuthResponse, ILoginData>({
    query: ({ email, password }) => ({ url: '/login', method: "POST", body: { email, password } }),
    invalidatesTags: ['Auth'],
    async onQueryStarted(_, { queryFulfilled }) {
      try {
        const { data } = await queryFulfilled
        localStorage.setItem('token', data.accessToken)
      } catch (err) {
        console.log(err)
      }
    },
  }),

(However, I would still like to know why data was possibly undefined in my question case.)