Search code examples
reactjsredux-toolkitrtk-query

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!


Solution

  • 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