重新渲染不会发生在使用 Tanstack 查询时。

huangapple go评论68阅读模式
英文:

Re-rendering is not happening while using Tanstack query

问题

我正在使用 Tankstack 查询来获取 API 数据。这是用于获取数据的自定义钩子,

import { useQuery } from "@tanstack/react-query";
import { ApiInstance } from "../axios/axios";
import { Endpoints } from "../endpoints/endpoints";

export const useGetApiDetails = (id) => {
  const { data, isLoading } = useQuery(["getApiDetails"], {
    queryFn: async () => {
      const { data } = await ApiInstance.get(Endpoints.getApiDetails(id));
      return data;
    },
  });
  return { data, isLoading };
};

这是我在哪里使用自定义钩子的地方,

const Home = () => {
  const { pathname } = useLocation();
  const id = pathname.replace("/", "");
  const { data, isLoading } = useGetApiDetails(id);
  const [apiDetails, setApiDetails] = useState();
  const [requestParamList, setRequestParamList] = useState();

  useEffect(() => {
    setApiDetails(data?.data?.apiDetails);
    setRequestParamList(data?.data?.requestParamList);
  }, [data]);

  return (
    <div className="w-full h-full flex">
      {/* {isLoading ? (
        <h1>Loading...</h1>
      ) : ( */}
      <>
        <LeftSide apiDetails={apiDetails} requiredParams={requestParamList} />
        <RightSide apiDetails={apiDetails} requiredParams={requestParamList} />
      </>
      {/* )} */}
    </div>
  );
};

export default Home;

我将 id 作为参数发送以获取特定数据。而且发送正常。但每当 id 更改时,UI 不会更新。只有当我导航到其他选项卡并返回时才会更新。同样,我尝试使用普通的 axios 获取方法进行获取,它看起来像这样,

const { pathname } = useLocation();
  const id = pathname.replace("/", "");
  const [apiDetails, setApiDetails] = useState();
  const [requestParamList, setRequestParamList] = useState();

  const fetchData = async (id) => {
      const response = await ApiInstance.get(Endpoints.getApiDetails(id))
      console.log(response.data, "res");
      setApiDetails(response.data.data.apiDetails)
      setRequestParamList(response.data.data.requestParamList)
  }

  useEffect((id) => {
    fetchData(id)
  }, [id]);

使用这段代码,UI 在点击更改 id 时会正确更新。我不知道为什么在使用 Tanstack 查询时不会发生这种情况。对此有任何帮助将不胜感激。

英文:

I'm fetching the API using Tankstack query. This is the custom hook to fetch the data,

import { useQuery } from &quot;@tanstack/react-query&quot;;
import { ApiInstance } from &quot;../axios/axios&quot;;
import { Endpoints } from &quot;../endpoints/endpoints&quot;;

export const useGetApiDetails = (id) =&gt; {
  const { data, isLoading } = useQuery([&quot;getApiDetails&quot;], {
    queryFn: async () =&gt; {
      const { data } = await ApiInstance.get(Endpoints.getApiDetails(id));
      return data;
    },
  });
  return { data, isLoading };
};

This is where I'm using the custom hook,

const Home = () =&gt; {
  const { pathname } = useLocation();
  const id = pathname.replace(&quot;/&quot;, &quot;&quot;);
  const { data, isLoading } = useGetApiDetails(id);
  const [apiDetails, setApiDetails] = useState();
  const [requestParamList, setRequestParamList] = useState();

  useEffect(() =&gt; {
    setApiDetails(data?.data?.apiDetails);
    setRequestParamList(data?.data?.requestParamList);
  }, [data]);

  return (
    &lt;div className=&quot;w-full h-full flex&quot;&gt;
      {/* {isLoading ? (
        &lt;h1&gt;Loading...&lt;/h1&gt;
      ) : ( */}
      &lt;&gt;
        &lt;LeftSide apiDetails={apiDetails} requiredParams={requestParamList} /&gt;
        &lt;RightSide apiDetails={apiDetails} requiredParams={requestParamList} /&gt;
      &lt;/&gt;
      {/* )} */}
    &lt;/div&gt;
  );
};

export default Home;

I'm sending the id as params to fetch the particular data. And it is sent fine. But whenever the id is changed, the UI is not getting updated. It only updates when I navigate to other tab and comes back. Same I tried fetching using normal axios get method. It looks like this,

const { pathname } = useLocation();
  const id = pathname.replace(&quot;/&quot;, &quot;&quot;);
  const [apiDetails, setApiDetails] = useState();
  const [requestParamList, setRequestParamList] = useState();

  const fetchData = async (id) =&gt; {
      const response = await ApiInstance.get(Endpoints.getApiDetails(id))
      console.log(response.data, &quot;res&quot;);
      setApiDetails(response.data.data.apiDetails)
      setRequestParamList(response.data.data.requestParamList)
  }

  useEffect((id) =&gt; {
    fetchData(id)
  }, [id]);

With this code, the UI is updating correctly whenever the Id is changed by clicking. I don't know why it is not happening when using Tanstack query. Any help on this would be appreciated.

答案1

得分: 4

你应该在查询键中添加id作为依赖项。这将唯一标识查询以便缓存它们并自动重新获取。

参考这个链接。

import { useQuery } from "@tanstack/react-query";
import { ApiInstance } from "../axios/axios";
import { Endpoints } from "../endpoints/endpoints";

export const useGetApiDetails = (id) => {
  const { data, isLoading } = useQuery(["getApiDetails", id], {
    queryFn: async () => {
      const { data } = await ApiInstance.get(Endpoints.getApiDetails(id));
      return data;
    },
  });
  return { data, isLoading };
};
英文:

You should add the id also as dependency in query keys. This will uniquely identify the query to cache them and refetch automatically.

Refer this

import { useQuery } from &quot;@tanstack/react-query&quot;;
import { ApiInstance } from &quot;../axios/axios&quot;;
import { Endpoints } from &quot;../endpoints/endpoints&quot;;

export const useGetApiDetails = (id) =&gt; {
  const { data, isLoading } = useQuery([&quot;getApiDetails&quot;, id], {
    queryFn: async () =&gt; {
      const { data } = await ApiInstance.get(Endpoints.getApiDetails(id));
      return data;
    },
  });
  return { data, isLoading };
};

huangapple
  • 本文由 发表于 2023年7月17日 23:54:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76706201.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定