John Z
John Z

Reputation: 161

RTK useLazyQuery trigger onClick data not refreshed

I'm a newbie on RTK queries and I currently have this problem

What i'm trying to do here is after trigger(), i need to access result in the onClickHandler to process, but when i console.log the result, i keep getting the initObject of

    {
      currentData: undefined
      data: undefined
      isError: false
      isFetching: false
      isLoading: false
      isSuccess: false
      isUninitialized: true
      status: "uninitialized"
    }

Here is a small snippet of the code

const ComponentA = (props) => {
   const [trigger, result] = useLazyQuery(); 

    const onClickHandler = () => {
       trigger();
       console.log(result);
    };

    return (
      <button onClick={onClickHandler}>Button</button>
    )

}

My question is what do i need to get the data that is coming back from the query?

Thank you very much!

Upvotes: 2

Views: 2447

Answers (2)

Harish M
Harish M

Reputation: 1

Even i had issue of getting undefined for data when tried to access directly from lazy query. const [triggerQuery, { data, isLoading, isError, error, isFetching }] = useLazyGetPlanWeekViewApiQuery();

But by using async and await on trigger() function, it works with lazy query.

const onClickHandler = async () => {
       const result = await triggerQuery(params);
console.log(result, 'result');
};

Upvotes: 0

johnhcody
johnhcody

Reputation: 36

One solution would be to unwrap it if you are using Redux Toolkit.

Something like this should work:

const ComponentA = (props) => {
const [trigger] = useLazyQuery(); 

const onClickHandler = async () => {
   const result = await trigger().unwrap();
   console.log(result);
};

return (
  <button onClick={onClickHandler}>Button</button>
)

}

https://redux-toolkit.js.org/api/createAsyncThunk#unwrapping-result-actions

Upvotes: 2

Related Questions