Search code examples
reactjsreduxreact-reduxrtk-query

useLazyQuery doesn't update data between all components


I'm currently using the useXXXLazyQuery hook of rtk query for handling the login of my page, the problem is that i don't have the latest data in my ProtectedRoute component.

The code is as following:

ProtectedRoute Component

import { type FC, type ReactNode } from 'react'
import { Navigate } from 'react-router-dom'
import { useLazyAuthQuery } from 'services/auth'

interface ProtectedRouteProps {
  children: ReactNode
}

const ProtectedRoute: FC<ProtectedRouteProps> = ({ children }) => {
  const [, results] = useLazyAuthQuery()

  if (results.data?.message !== 'authenticated') {
    return <Navigate to="/" replace />
  }

  return children
}

export { ProtectedRoute }

And that's when i call the lazyQuery hook:


  ...
  const navigate = useNavigate()
  const [trigger, results] = useLazyAuthQuery()

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    const data = new FormData(event.currentTarget)

    trigger({
      username: data.get('username'),
      password: data.get('password'),
    })
      .unwrap()
      .then(() => {
        navigate('/table')
      })
  }
  ...

The results of the useLazyAuthQuery on the ProtectedRoute component is always uninitialized so whenever I try to login the ProtectedRoute component acts as it should leaving me out of the Application. How can I access the latest data on the ProtectedRoute component?


Solution

  • You misunderstand useLazyQuery. useLazyQuery is a hook that will always start "unattached" and then allows you to execute the trigger function to attach this one hook instance to a query (or start a new one). But each useLazyQuery is on it's own - calling the trigger function of one will not trigger all others, as in the end they could all have different arguments to their endpoint.