skip to Main Content

Why doesn’t my second call to personDataSend set isLoading value work in the RTK Query mutation query? When you do onClick for the first time, isLoading is true, but on the second click, it is not, and on the second one, the value remains false.

const [
  getDriverLicenseByPin,
  { data, isLoading },
] = useLazyGetDriverLicenseByPinQuery();
  
const personDataSend = (values) => {
  getDriverLicenseByPin({
    pin: values.Pin,
    driverLicenseNumber: values.DriverLicenseNumber,
  });
};

2

Answers


  1. RTK will cache the result. If you want to re-fetch you will have to invalidate that part of your store first.

    https://redux-toolkit.js.org/rtk-query/usage/automated-refetching

    Login or Signup to reply.
  2. Queries only load once really, e.g. when no data has been cached yet. You likely want to use the isFetching status which is true whenever the query is actively fetching.

    See useLazyQuery:

    type UseQueryStateResult<T> = {
      // Base query state
      originalArgs?: unknown // Arguments passed to the query
      data?: T // The latest returned result regardless of trigger arg, if present
      currentData?: T // The latest returned result for the trigger arg, if present
      error?: unknown // Error result if present
      requestId?: string // A string generated by RTK Query
      endpointName?: string // The name of the given endpoint for the query
      startedTimeStamp?: number // Timestamp for when the query was initiated
      fulfilledTimeStamp?: number // Timestamp for when the query was completed
    
      isUninitialized: false // Query has not started yet.
      isLoading: false // Query is currently loading for the first time. No data yet.
      isFetching: false // Query is currently fetching, but might have data from an earlier request.
      isSuccess: false // Query has data from a successful load.
      isError: false // Query is currently in an "error" state.
    }
    

    Update your logic to also reference the isFetching status, which should be true when the query endpoint is re-triggered/re-fetching.

    const [
      getDriverLicenseByPin,
      { data, isLoading: isLoadingData, isFetching },
    ] = useLazyGetDriverLicenseByPinQuery();
    
    const isLoading = isLoadingData || isFetching;
      
    const personDataSend = (values) => {
      getDriverLicenseByPin({
        pin: values.Pin,
        driverLicenseNumber: values.DriverLicenseNumber,
      });
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search