RTK-query aims for the params when it should skip

22 views Asked by At

RTK-query accepts skip option to skip the request when the option is true:

const {data} = useGetMyDataQuery(myParams, {skip: myCondition});

I expect the skip is being checked before it accesses myParams and skip running that code when it's supposed to be skipped.

For example in the following code, I expect the function not be run when myCondition is true.

const getMyParams = () => params; 
const {data} = useGetMyDataQuery(getMyParams(), {skip: myCondition});

In this example I'm getting the parameters from an object which is possibly undefined. I skip the call when the object is undefined, so I expect the parameter code only runs when the condition is met. But it's not the case and you can see it gives a null pointer error when you click on "Add empty" button.

Is it the normal behavior of RTK-query or am I doing something wrong?

1

There are 1 answers

0
phry On BEST ANSWER

That has nothing to do with RTK Query, that's how JavaScript works.

useGetMyDataQuery is a function, and arguments are evaluated before they are passed to the function. RTK Query has no knowledge if you write myParams or getMyParams() there - it only ever sees the final value.

You can use skipToken instead here:

import {skipToken} from '@reduxjs/toolkit/query'
const {data} = useGetMyDataQuery(myCondition ? skipToken : getMyParams());