I have a custom react hook which is used to get a user’s data by sending a POST request. I would like my custom react hook to check if the argument passed into the hook meets certain conditions, however I’m aware that I cant use conditions with hooks. Does any one have any idea how to improve my code so that I can check if an argument is valid?
...
import { useQuery } from "@tanstack/react-query";
export const useLiquidityPositions = (userAddress: string): GraphQLResponse<LiquidityPositions> => {
const {
status: status,
isLoading: loading,
error: error,
data: response,
} = useQuery({
queryKey: ["USER_POSITIONS", userAddress],
queryFn: async () => {
if (!isAddress(userAddress)) {
return undefined
}
const res = await getLiquidityPositionsData(userAddress);
return res;
}});
const payload = response?.data;
return { status, loading, error, response, payload }
}
2
Answers
You can enable or disable useQuery by your condition
like this :
and in usage:
Two ways to validate query using react-query.
1. only validate a single request. https://react-query-v3.tanstack.com/guides/dependent-queries
2. validate all request.
https://react-query-v3.tanstack.com/guides/query-invalidation
Add validate functions to queryClient