[英]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
.使,不允许使用
useQuery
内useEffect
。
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.