如何在每次输入更改时获取现有缓存数据?

How to fetch existing cache data on every input change?

我的应用程序有一个用户 input 和一个 id 作为 request 发送,并呈现与 id 匹配的 response data

如果 data 已经存在于 cache 中,我希望应用程序在每个 input change 上从 cache 中获取。

如果 data 不存在于 cache 中,应用程序只能通过让用户单击 submit button 来发送 request

一旦用户输入 input,我将访问 cache 并检查每个 input change 上是否存在当前输入 id。如果是这样,渲染 datasubmit buttondisabled。否则 enable submit button 以便用户可以发送 request.

根据研究,React Query's queryClient.getQueryCache 是我认为我需要的。我会通过在 queryCache 上使用 .includes 来检查输入 id 是否存在于 cache 中。以后怎么办?这是实现功能的正确方向吗?

这是我当前的设置。请让我知道如何继续实施所请求的功能。 https://codesandbox.io/s/rick-and-morty-2gy8r?file=/src/App.js

const handleRickAndMortyFetch = () => {
  return delay()
    .then(() => axios(`https://rickandmortyapi.com/api/character/${idQuery}`))
    .then((res) => res.data);
  };

const cacheData = queryClient.getQueryData(["rickandmorty", idQuery], {
    exact: false
})

const onInputChange = event => {
    setIdQuery(event.target.value, () => {
        cacheData.includes(idQuery)
            handleRickAndMortyFetch()
    })
}

const disable = isLoading || parseFloat(formId) === idQuery || !idQuery || cacheData?.id === idQuery;

<form onSubmit={handleSubmit(onSubmit)}>
  <input
    type="number"
    name="rickAndMortyId"
    placeholder="Between 1 and 671"
    ref={register}
    disabled={isLoading}
    onChange={onInputChange}
  />
  <button type="submit" disabled={disable}>
    Search Character
  </button>
</form>

我想你想要的是queryClient.getQueryData(["rickandmorty", idQuery])。这将为您提供缓存中特定 queryKey 的数据。如果是 undefined,您的缓存中没有该键的数据,因此您可以启用提交按钮。

但是你需要让react-query为你管理数据。这意味着你的 handleRickAndMortyFetch 函数应该 return 一个 Promise - 不需要使用本地状态(rickAndMortyCharacter) - 这只是 data 属性 return 来自 react-query