How to fetch existing cache data on every input change?

Viewed 133

My application has a user input an id to send as a request and the response data that matches that id is rendered.

If the data already exist in the cache, I'd like the application to fetch from the cache on each input change.

If the data does not exist in the cache, the application can only send the request by having the user click the submit button.

Once a user types in the input, I would access cache and check if the current input id exists on every input change. If so, render the data while the submit button is disabled. Else enable the submit button so that the user can send the request.

From research, React Query's queryClient.getQueryCache is what I believe I need. I would check to see if the input id exists in the cache by using .includes on queryCache. What would I do afterwards? Is this the correct direction to implement the functionality?

Here is my current setup. Please let me know how to move forward implementing the requested functionality. 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>
1 Answers

I think what you want is queryClient.getQueryData(["rickandmorty", idQuery]). This will give you data from the cache for a specific queryKey. If that is undefined, you have no data in the cache for that key, so you can enable the submit button.

But you need to let react-query manage the data for you please. That means your handleRickAndMortyFetch function should return a Promise - there is no need to use local state (rickAndMortyCharacter) - this is just the data property returned from react-query

Related