Redux RTK query invalidatesTags not called after mutation

Viewed 1100

I've been trying to figure out why tag invalidation is not working and added some logging. The providesTags in getMe works fine, but invalidatesTags in login is never called. What might be wrong?

I have a redux RTK query API like this:

const baseQuery = fetchBaseQuery({
  baseUrl: baseUrl,
  prepareHeaders: (headers, { getState }) => {
    const token = getState().auth.token
    if (token) {
      headers.set('authorization', `Bearer ${token}`)
    }
    return headers
  },
})

export const api = createApi({
  baseQuery: baseQuery,
  tagTypes: ['User'],
  endpoints: build => ({
    login: build.mutation({
      query: code => ({
        url: `auth/login/?code=${code}`,
        method: 'POST',
      }),
      invalidatesTags: (result, error, arg) => {
        console.log('auth/login', result, error, arg)
        return ['User']
      },
    }),
    getMe: build.query({
      query: () => 'auth/me',
      providesTags: result => {
        console.log('auth/me', result)
        return ['User']
      },
    }),
  }),
})

export const { useLoginMutation, useGetMeQuery } = api

login is called on component mount when the page is loaded from a callback like this:

const CallbackComponent = () => {
  const location = useLocation()
  const [login, { isUninitialized, isLoading, isError, data, error }] = useLoginMutation()

  useEffect(() => {
    if (isUninitialized) login(getCode(location))
  })
  ...
}

getMe is used in a component like this:

const Header = () => {
  const isAuthenticated = useIsAuthenticated()
  const {
    data: user,
    isError,
    error,
  } = useGetMeQuery(null, {
    skip: !isAuthenticated,
  })

  if (isError) return <span>{JSON.stringify(error)}</span>

  return (
    <nav className="header">
      {user ? <CharacterList characters={user.characters} /> : null}
      {!user || user.characters.length === 0 ? <Login /> : null}
    </nav>
  )
}
1 Answers
Related