0

I am using tanstack-query and have dependent queries to do:

const { resourceId } = useGetResourceId(); // resourceId: number | null
const { data, loading, error } = useGetResourceData(resourceId);

How can I tell useGetResourceData hook to wait with API call to retrieve resource data, until I have valid resourceId from hook above?

2 Answers 2

2

This is how to ensure resourceId is available and valid before useGetResourceData query is being called.


const useGetResourceData = (resourceId: number | null) => {
    return useQuery({
      queryKey: ['resource-data', resourceId], // Cache key scoped to the specific resource ID
      queryFn: () => fetchResourceData(resourceId!), //fetchResourceData is the funtion containing the api call/method
      enabled: !!resourceId, // Waits until resourceId is truthy
    });
  };
Sign up to request clarification or add additional context in comments.

Comments

1

You can keep the second query from firing using a property called enabled as:

const { data: resourceId } = useGetResourceId();
const { data, isLoading, error } = useGetResourceData(resourceId, {
  enabled: !!resourceId // Query won't run until resourceId is truthy
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.