Search code examples
reactjsreduxreact-reduxrtk-query

RTK Query prevent data.data


I'm following RTK Query tutorial at https://redux-toolkit.js.org/rtk-query/usage-with-typescript.

I have the following endpoint:

const myApi = myBaseApi.injectEndpoints({
    endpoints: build => ({
        myMethod: build.query<MyClass, void>({
            query: () => 'path/to/endpoint',
        }),
    }),
    overrideExisting: false,
});

However when I use the hook for this query like below:

const q = useMyMethod()

q.data is strongly typed to MyClass which is perfect. However when I run the app, q.data is a fetch response object, with another data property which actually is the MyClass instance. In other words, I need to type q.data.data to access the actual data. In the examples this isn't the case. What am I doing wrong and how can I access q.data as MyClass directly without involving fetch response?


Solution

  • It's not a "fetch response" object. The query hooks return an object that contains the actual fetched and cached value as data, plus a number of status flag fields:

    const { data , isFetching } = useSomeQuery()
    

    See the list of fields here:

    If you're saying that there's another data field nested inside, then that's likely coming from your actual API response, because RTKQ just saves whatever value your API response returned. I'd suggest checking both the server side and the network response tab to see what's being returned from the server.

    Also, the expectation is that the fetched value is plain JS objects and arrays. When you say MyClass, that makes it sound like you expect this to be an actual JS class instance, and RTKQ will definitely not create a class instance for you - it just does the usual fetch().then(r => r.json()) processing for you.