简体   繁体   English

react-query:仅当状态变量改变时重新获取查询

[英]react-query: Refetch Query only if the state variable is changed

I have a select option menu.我有一个选择选项菜单。 So, When a user selects an option, I want send a GET/ request to the server with that option and recieve the filtered data from server.因此,当用户选择一个选项时,我想使用该选项向服务器发送 GET/ 请求,并从服务器接收过滤后的数据。

This can be achived using useEffect(() => {// send the request}, [criteria])这可以使用 useEffect(() => {// send the request}, [criteria]) 来实现

Because, useEffect ensures that the request will send to server only if the setCriteria is finished.因为,useEffect 确保只有在 setCriteria 完成后请求才会发送到服务器。

But, I am using react-query library.但是,我正在使用react-query库。 so that, it is not allowed to use useQuery inside useEffect .使,不允许使用useQueryuseEffect

As A result, the request is send to server before it the setState is completed.结果,请求在 setState 完成之前发送到服务器。 So that, server gets the previous selected value, not the currently selected value.这样,服务器将获得先前选择的值,而不是当前选择的值。

onChange:更改:

<select
  name="filter"
  value={criteria}
  onChange={async (e) => {
    setCriteria(e.target.value);
  }}
>
  <option>Most recent First</option>
  <option>Price: Low to High</option>
  <option>Price: High to Low</option>
</select>;

Fetch posts:获取帖子:

 const FetchPosts = async () => {
    const {
      data: { posts },
    } = await axios.get(`${process.env.API_URL}/api/posts`, {
      params: {
        filter: criteria,
      },
    });

    return posts;
  };

 useQuery("posts", FetchPosts);

 const posts = queryCache.getQueryData("posts");

You can use your criteria as query key.您可以使用您的条件作为查询键。 Whenever a query's key changes, the query will automatically update.每当查询的键更改时,查询将自动更新。

const FetchPosts = async ({criteria}) => {
    console.log(criteria) //from useQuery key

    //your get api call here with criteria params

    return posts;
};

const [criteria, setCriteria] = useState("")

const {isLoading, data: post} = useQuery(["posts", criteria], FetchPosts); //include criteria state to query key

console.log(post) 

<select
  name="filter"
  value={criteria}
  onChange={(e) => {
    setCriteria(e.target.value);  // trigger a re-render and cause the useQuery to run the query with the newly selected criteria
  }}
>
  <option>Most recent First</option>
  <option>Price: Low to High</option>
  <option>Price: High to Low</option>
</select>

Question is already answered.问题已经回答了。 Here's my two cents:这是我的两分钱:

Treat useQuery's query keys like a dependency array of useEffect.将 useQuery 的查询键视为 useEffect 的依赖数组。 Whenever the key changes query gets executed.每当键更改查询被执行时。

If you still want to control the firing of queries, you may explore the "enabled" option to the useQuery hook.如果您仍然想控制查询的触发,您可以探索 useQuery 钩子的“启用”选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 react-query:当且仅当没有错误时重新获取 - react-query: Refetch if and only if there is no error 如何仅在第一次点击时通过 react-query 获取数据,然后在后续点击时禁用重新获取 - How to fetch data only on first click via react-query and then disable refetch on subsequent clicks 反应查询:如果出现错误,不要在间隔内重新获取 - react-query: don't refetch on an interval if there is an error react-query,refetch 不会触发 useEffect - react-query, refetch don't trigger useEffect React-query - 组件挂载时重新获取数据 - React-query - refetch data when component mounts 如何使用 react-query 从兄弟组件重新获取查询 - How to refetch queries from sibling component with react-query 如何在 React-Query 中重新获取等待 POST - How to make a refetch wait for a POST in React-Query React-Query / React Router V5 将 state 变量从 api 响应插入到路由中,但仅在响应完成时 - React-Query / React Router V5 insert state variable from api response into route but only when response has finished 如果使用 react-query 和 next.js 编辑过滤器,则预取初始数据并重新获取 - Prefetching initial data and refetch if filter is edited using react-query and next.js 如何在 onClick 之后禁用重新调用 API 并执行重新获取 react-query 钩子? - How to disable re-calling API after onClick and execute refetch the react-query hook?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM