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
I found the way to avoid this problem by using
onQueryStarted
and generally it seems to be better approach:(However, I would still like to know why
data
was possibly undefined in my question case.)