可以将 queryFn 传递给 useQuery 吗?

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

Is it possible to pass queryFn to useQuery?

问题

我的queryFn是从上下文中获取的,尽管听起来很愚蠢:

```typescript
const fetch = useAppFetch()

由于历史原因,我不能更改这个,所以我想知道在使用时是否可以传递queryFn?

const fetch = useAppFetch()
const { data } = useDynamicQuery(
  { ...args },
  { queryFn: React.useCallback((args) => fetch(args), [fetch]) }
})

<details>
<summary>英文:</summary>

As stupid as it sounds, my queryFn is taken from the context:

```typescript
const fetch = useAppFetch()

I can't change this for historical reasons, so I'm wondering if it's possible to pass in queryFn when using it?

const fetch = useAppFetch()
const { data } = useDynamicQuery(
  { ...args },
  { queryFn: React.useCallback((args) =&gt; fetch(args), [fetch]) }
})

答案1

得分: 1

这是一个奇怪的设计模式,但有时我们必须使事情正常工作。

根据您的评论,似乎您已经找到了实现方式:
> @Philisonstrike 是的,我尝试将queryFn作为参数传递,但是我收到了一个警告:“在状态中检测到了一个非可序列化的值”,这个方法可以工作,但似乎不是推荐的方式。

我不太理解的是,您是如何在状态中得到一个非可序列化的值的。您的操作中不可避免地会有一个非可序列化的值,但这不是问题(它由thunk中间件解决)。

您是否以某种方式将queryFn参数存储在状态中?serializeQueryArgs API选项的默认实现应该已经处理了它的移除。我能想象到的唯一可能原因是,如果您已经设置了自己的serializeQueryArgs选项,并且它没有对所有内容进行序列化。

更有可能的情况是,queryFn本身以非可序列化的格式返回其数据。如果是这样,那么您奇怪的设置可能是问题的根本原因。

您需要追踪下非可序列化值的详细信息,然后从那里解决问题。

您还没有展示您的实现,所以我不知道可能发生的问题是什么。

英文:

It's a bizarre design pattern but sometimes we've got to make things work.

It seems like you figured out the implementation, based on your comment:
> @Philisonstrike Yes, I've tried passing queryFn as a parameter, but I get a warning: "A non-serializable value was detected in the state" , which works, but doesn't seem to be the recommended way.

What I'm not understanding is how you are getting a non-serializable value in your state. You will inevitably have a non-serializable value in your action but that's not a problem (it's solved by thunk middleware).

Are you are storing the queryFn argument in the state somehow? The default implementation of the serializeQueryArgs API option should have handled removing it. The only way I can imagine this being the cause is if you're already setting your own serializeQueryArgs option and it's not serializing everything.

It seems more likely that the queryFn itself is returning its data in a non-serializable format. In which case your bizarre setup it's really the culprit.

You need to track down the details of where and what this non-serializable value is and go from there.

You haven't shown your implementation so I don't know what issues might be occurring there.

huangapple
  • 本文由 发表于 2023年6月26日 15:34:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76554470.html
匿名

发表评论

匿名网友

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

确定