Reputation: 93
I'm having problem with making some useQuery chained fetching data I have asked around but can't make it to work,
there is a list of Categories that I want to fetch from API , axios.get("categories") then i want to fetch the subcategories based on the Categories list: axios.get("tutorials/{categoriesName}")
and i want to use UseQuery hook so i can handle the cache and stop unnecessary reRenders, i already have accomplished this with simple useEffect but the site renders so slowly so i want to learn the useQuery method ,
function AllCategories() {
const { isLoading, error, data, isFetching } = useQuery("categories", () =>
axios.get("/categories").then((res) => res.data)
);
console.log(data);
if (isLoading) return "Loading...";
if (error) return "An error has occurred: " + error.message;
//there are like 5 MAIN categories which i have used useQuery to fetch and handle Caching ,
//here i want to get the subcategories from each Main Category , can i chain useQueries ?
return (
<div>
{data.map((item) => {
return <div>{item.name}</div>;
})}
<div>{isFetching ? "Updating..." : ""}</div>
<ReactQueryDevtools initialIsClose />
</div>
);
}
export default AllCategories;
i dont know the correct way to approach this , because none of the examples have multiple dependent useQueries chained , im not sure even if this is possible ,
just to clarrify i want to render the data in Ui like this : PartentCategoryA..subCategorya .PartentCategoryB..subCategoryb PartentCategoryC..subCategoryc and not PartentCategoryA.PartentCategoryB PartentCategoryC .subCategorya ...subCategoryb ..subCategoryc thats what makes this task harder than it should be
this is without reactQuery:
export default function AllCategoriesPage() {
const [categories, setCategories] = useState([]);
const [finalList, setFinalList] = useState([]);
useEffect(() => {
axios.get("/categories").then((response) => {
setCategories(response.data);
});
}, [categories.length]);
useEffect(() => {
setFinalList(categories);
categories.map(async (category) => {
await axios
.get(`/categories/${category.name}`)
.then((res) => {
const mysub = res.data;
category.subCategories = mysub;
})
.then(() => {
setFinalList([...categories]);
});
});
}, [categories.length]);
return (
<div className="allCategoriesPage-wrapper">
{finalList.length === 0 && (
<div className="loader-container">
<Loader />
</div>
)}
<div className="allCategoriesPage-container">
{finalList.length > 0 &&
finalList.map((category) => {
return (
<React.Fragment>
<div className="single-category-wrapper-main-cat ">
{category.name}
</div>
{category.subCategories &&
category.subCategories.map((subcategory) => {
return (
<Link to={`/categories/${subcategory.name}`}>
<div className="single-category-wrapper">
{subcategory.name}
<div className="single-category-img-container">
<img
className="single-category-image"
src={`http://localhost:3001/tutorials/${subcategory.name}/avatar`}
></img>
</div>
</div>
</Link>
);
})}
</React.Fragment>
);
})}
</div>
</div>
);
}
thanks in advance
Upvotes: 6
Views: 8661
Reputation: 31250
A good way to do this is with what React Query's "Dependent Queries" docs page says ( https://react-query.tanstack.com/guides/dependent-queries ): call all the useQuery hooks you need, but send "enabled: false" until the data of the first is received correctly.
Otherwise it's a little complicated because a component always has to call the same hooks in the same order. So after the if statements you can't call further hooks.
Another solution is to split your code into smaller components, each with one useQuery call. In this case, you could split off roughly everything that is in the finalList.map()
function into its own component, and then that can do the second call to useQuery to get the subcategories. And so on. It seems strange at first but it's nice that it results in very compact components.
However, React Query recommends the enabled flag itself.
Upvotes: 5