2

I built a form using react,react-query,

link to the code

I built custom fields:

  • CacheAutocompleteField - cache field using react-query

    • queryAsyncFunc props - get async function and cache the data using react-query

I have 3 fields:

  • Type - Select field

  • Country - CacheAutocompleteField

  • City - CacheAutocompleteField

My scenario:

I select any type from my hardcoded list (Type A, Type B , Type C),

I search any country, then I search any city

What I'm trying to do?

  • every time I select a new type (from type options) - I want the country and city fields to be reset.
  • every time I already search the same key (the queryKey is combined of cacheKey+inputValue) , it will not call to api, it will get the results from cache (that's what I chose to use from react-query to do).

What I'm getting when I run my code?

  • When I select a type A, enter a country “Island” it will fetch data from api and get the data. Then when I select a type B, enter a country “Island” - It will fetch data from api and get the data. But when I select a type A and and same country “Island” again - I don’t want it to fetch data from api - I want it to get data from cache (that’s the reason I chose to work with react-query too) because it already search for this data with the same type. The queryKey is depended of other type field.

  • when I search anything from autocomplete and it not find it, then I try to reset it by select any other type, it will kind of reset the value of the input but it still exist in inputValue of the country. for example I select type C, then enter "lakd" in country, then select any other type, it not reset it. reset works for me only when anything find in autocomplete and I select it. I guess it's because the autocomplete component not have inputValue props, but when I use it it make me other issues.

enter image description here

1 Answer 1

2

You needn't call refetch. It call the API regardless of the cache. Comment/Remove this code

  // useEffect(() => {
  //   if (debounceInputValue.length > 1) {
  //     refetch();
  //   }
  // }, [debounceInputValue, refetch]);

And you should enable the useQuery

enabled: true,

And use debounceInputValue instead of inputValue for useQueryData

https://codesandbox.io/s/react-query-autocomplete-forked-d84rf4?file=/src/components/FormFields/CacheAutocompleteField.tsx:1255-1263

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.