最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - chaining reactQuery calls - Stack Overflow

programmeradmin3浏览0评论

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 acplished 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

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 acplished 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

Share Improve this question asked Apr 23, 2021 at 11:37 Alisa khAlisa kh 931 silver badge8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

A good way to do this is with what React Query's "Dependent Queries" docs page says ( https://react-query.tanstack./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 plicated because a ponent 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 ponents, each with one useQuery call. In this case, you could split off roughly everything that is in the finalList.map() function into its own ponent, 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 pact ponents.

However, React Query remends the enabled flag itself.

发布评论

评论列表(0)

  1. 暂无评论