tRPCttRPC
Powered by
sayanaS
tRPC•3y ago•
4 replies
sayana

useQuery first refetch returns undefined

Hello.
So, I'm trying to get an item by ID when the user clicks a button. I've searched around and found a way to do it by using
useState()
useState()
for the ID, setting
useQuery
useQuery
's
enabled
enabled
to
false
false
, and
refetch()
refetch()
whenever I need to get the item.

const [itemId, setItemId] = useState("");
const getItemById = api.items.getById.useQuery(
  { id: itemId },
  { enabled: false },
);

const getItemById = (id: string) => {
  setItemId(id);
  getItemById
    .refetch()
    .then((result) => {
      if (result.data) {
        console.log(result.data);
      }
    })
    .catch((err) => {
      // empty
    });
};
const [itemId, setItemId] = useState("");
const getItemById = api.items.getById.useQuery(
  { id: itemId },
  { enabled: false },
);

const getItemById = (id: string) => {
  setItemId(id);
  getItemById
    .refetch()
    .then((result) => {
      if (result.data) {
        console.log(result.data);
      }
    })
    .catch((err) => {
      // empty
    });
};

The problem is, the first
refetch()
refetch()
always returns
undefined
undefined
, so the user has to click the button twice to get the item.
I've looked around and the problem seems to be about re-rendering . There's a possible answer, but it uses
onSuccess
onSuccess
which will be deprecated soon.
https://stackoverflow.com/questions/75447288/reactquery-returns-undefined-as-the-first-result-then-returns-the-data
Is there a solution to this? Or perhaps a better way to get an item with ID as input on demand?
I'm using Node 18.
Stack Overflow
reactQuery returns undefined as the first result, then returns the ...
So, I'm trying to fetch data -onClick- using reactQuery and to store the response in a variable.
const { data: response, refetch } = useQuery({
queryKey: ['get-response'],
queryFn: async() ...
reactQuery returns undefined as the first result, then returns the ...
Solution
If you want to use the value imperatively you might want to use the vanilla client (via useUtils().client) or a mutation instead
Jump to solution
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

getInfiniteData returns undefined
davidgonmarDdavidgonmar / ❓-help
3y ago
createTRPCNext config ctx always returns undefined.
MonkeyStructMMonkeyStruct / ❓-help
3y ago
Data from useQuery is inferred as data: {} | undefined
zirkelcZzirkelc / ❓-help
3y ago