获取查询时数据未更新 - React-Query?
Data Not updated when fetch query - React-Query?
我有一个三选框类型,
当我选中任何框时,我会在 useEffect()
中调用 refetch()
。
第一次,我选中了所有复选框,return 是预期的数据!
但在某些情况下“随机更改复选框”,来自 API 的 returned 数据是“未定义的”虽然 return是 Postman!
中的预期数据
所以我想我是否需要为我想要获取的每个数据提供一个唯一的queryKey
所以我提供了一个随机值“Date.now()”但仍然return未定义
代码片段
type bodyQuery = {
product_id: number;
values: {};
};
const [fetch, setFetch] = useState<number>();
const [bodyQuery, setBodyQuery] = useState<bodyQuery>({
product_id: item.id,
values: {},
});
const {
data: updatedPrice,
status,
isFetching: loadingPrice,
refetch,
} = useQuery(
['getUpdatedPrice', fetch, bodyQuery],
() => getOptionsPrice(bodyQuery),
{
enabled: false,
},
);
console.log('@bodyQuery: ', bodyQuery);
console.log('@status: ', status);
console.log('@updatedPrice: ', updatedPrice);
useEffect(() => {
if (Object.keys(bodyQuery.values).length > 0) {
refetch();
}
}, [bodyQuery, refetch]);
export const getOptionsPrice = async (body: object) => {
try {
let response = await API.post('/filter/product/price', body);
return response.data?.detail?.price;
} catch (error) {
throw new Error(error);
}
};
所以在聊天中经过一番阐述,这个问题可以通过利用 useQuery 键数组来解决。
因为它的行为类似于 useEffect
中的依赖数组,所以定义结果数据的所有内容都应该插入其中。而不是触发refetch
更新数据。
此处的密钥可能如下所示:['getUpdatedPrice', item.id, ...Object.keys(bodyQuery.values)],如果这些值在初始渲染时发生变化。
我有一个三选框类型,
当我选中任何框时,我会在 useEffect()
中调用 refetch()
。
第一次,我选中了所有复选框,return 是预期的数据!
但在某些情况下“随机更改复选框”,来自 API 的 returned 数据是“未定义的”虽然 return是 Postman!
中的预期数据所以我想我是否需要为我想要获取的每个数据提供一个唯一的queryKey
所以我提供了一个随机值“Date.now()”但仍然return未定义
代码片段
type bodyQuery = {
product_id: number;
values: {};
};
const [fetch, setFetch] = useState<number>();
const [bodyQuery, setBodyQuery] = useState<bodyQuery>({
product_id: item.id,
values: {},
});
const {
data: updatedPrice,
status,
isFetching: loadingPrice,
refetch,
} = useQuery(
['getUpdatedPrice', fetch, bodyQuery],
() => getOptionsPrice(bodyQuery),
{
enabled: false,
},
);
console.log('@bodyQuery: ', bodyQuery);
console.log('@status: ', status);
console.log('@updatedPrice: ', updatedPrice);
useEffect(() => {
if (Object.keys(bodyQuery.values).length > 0) {
refetch();
}
}, [bodyQuery, refetch]);
export const getOptionsPrice = async (body: object) => {
try {
let response = await API.post('/filter/product/price', body);
return response.data?.detail?.price;
} catch (error) {
throw new Error(error);
}
};
所以在聊天中经过一番阐述,这个问题可以通过利用 useQuery 键数组来解决。
因为它的行为类似于 useEffect
中的依赖数组,所以定义结果数据的所有内容都应该插入其中。而不是触发refetch
更新数据。
此处的密钥可能如下所示:['getUpdatedPrice', item.id, ...Object.keys(bodyQuery.values)],如果这些值在初始渲染时发生变化。