Hi All,
I'm basically trying to make a custom hook which allows multiple queries to be executed and then all of the results get merged together into a single result set.
I currently have this however this doesn't work as the size of result changes between renders as rootData can start as an empty array.
Inspired from: https://github.com/TanStack/query/issues/3049
const { data: rootData } = useQuery(...query); // rootData can start as a empty array
const queries = useMemo(() => rootData.map(()=> (...query), [rootData]);
const result = useQueries(queries);
const isInitialLoading = useMemo(() => results?.some((result) => result.isInitialLoading), [...results.map((qr) => qr.isInitialLoading)]);
const isSuccess = useMemo(() => results?.every((result) => result.isSuccess), [...results.map((qr) => qr.isSuccess)]);
const isError = useMemo(() => results?.some((result) => result.isError), [...results.map((qr) => qr.isError)]);
const isLoadingError = useMemo(() => results?.some((result) => result.isLoadingError), [...results.map((qr) => qr.isLoadingError)]);
const resultData = results.map((qr) => qr.data);
const data = useMemo(
() => results?.reduce((acc, result) => (result?.data ? [...acc, ...result.data] : acc), []),
[...results.map((qr) => qr.data)]
);
return useMemo(() => {
return {
isInitialLoading,
isSuccess,
isError,
isLoadingError,
data
};
}, [isInitialLoading, isSuccess, isError, isLoadingError, data]);
ERROR: The final argument passed to useMemo changed size between renders. The order and size of this array must remain constant.
Due to our unique use case the combined results from this query need to then be passed into another useQueries.
So I'm trying to work out how to achieve this while also reducing the number of renders as much as possible as the renders will cascade to the next hook.
Without the useMemos I currently I keep getting into a infinite render loop due to a object ref change on each render.
Any suggestions how best to achieve this?