Refresh the React query even if the key is already present in the cache

I recently developed a form using a combination of technologies including react, react-query, material ui, formik, and yup for schema validation.

Check out the code here

Custom fields I created:

  • SelectField

  • AutocompleteField

  • CacheAutocompleteField - caching field with react-query integration

    • queryAsyncFunc props - to cache data retrieved from an async function using react-query

The form includes 3 main fields:

  • Type - Select field

  • Country - CacheAutocompleteField

  • City - CacheAutocompleteField

Scenario:

First, choose a type from Type A, Type B, or Type C,

Next, search for a country, followed by searching for a city

Objective:

  • Whenever a new type is selected, reset the values in the country and city fields.
  • If the same key has been previously searched (based on the queryKey), retrieve results from the cache instead of making another API call using react-query.

Current Issue Encountered:

  • When selecting Type A and entering "Island" as the country, it fetches data from the API correctly. However, when switching to Type B and entering "Island" again, it should not re-fetch from the API but retrieve data from the cache instead. This behavior aligns with the use of react-query as intended.

  • If I search for something through autocomplete and it does not find a match, trying to reset it by choosing a different type might not completely clear the input value. For instance, after selecting Type C and typing "lakd" as the country, switching to any other type does not fully reset the input. This issue seems related to the autocomplete component lacking proper handling of inputValue props, which can lead to undesired outcomes.

https://i.stack.imgur.com/EN9Wi.png

Answer №1

One way to address your initial concern is by utilizing the enable property of react-query in conjunction with debounceInputValue.

You can manage this by using a boolean state to enable and disable it, and within the useEffect for debounceInputValue, set it to true when applicable, then back to false once the data is received.

Here's an example:

  const [queryStatus, setQueryStatus] = useState(false);

 const { data, isFetching, refetch } = useQueryData(
    cacheKey,
    inputValue,
    queryAsyncFunc,
    queryStatus
  );

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


  useEffect(() => {
    setDataOptions(data ? [...data] : []);
    setQueryStatus(false);
  }, [inputValue, data]);

Also, ensure you include the following in useQuery:

enabled: enabled,
staleTime: Infinity,

To tackle your second issue, I resolved it by establishing state for inputValue and implementing onChange for it.

Here's how you can do that:

  const onInputChange = (_,newInputValue)=>{
    setInputValue(newInputValue);
  }

Make sure to apply the inputValue and onInputChange in autoComplete as well:

 inputValue={inputValue}
 onInputChange={onInputChange}

For further reference, check out this Codesandbox.

Answer №2

There is no need to call the refetch function. The API will be called regardless of the cache status. You can comment out or remove this code snippet:

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

Make sure you enable the use of useQuery:

enabled: true,

Also, replace occurrences of inputValue with debounceInputValue in the useQueryData.

For more information, visit this link: https://codesandbox.io/s/react-query-autocomplete-forked-d84rf4?file=/src/components/FormFields/CacheAutocompleteField.tsx:1255-1263

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for saving the state of a component in localStorage

I attempted to save a value in local storage by setting the functional chart state, but encountered an error. Error: TypeError: Converting circular structure to JSON The chart state is defined as follows: const [chart, setChart] = useState([ emp ...

React struggling to retrieve the initial value from localStorage

Hello everyone! I am currently working on a MERN app and have been exploring how to implement JWT token authentication. Everything seems to be working fine, but I encountered a small issue on the frontend. After a user logs in, the token is successfully se ...

What causes React JS to continuously render in an infinite loop when using hooks and useState

I am struggling with updating the current state of my component based on a result using a custom hook in React. Whenever I try to update it, I end up in an infinite loop rendering due to my usage of the useState() hook. I am still new to working with Rea ...

Flex column MUI Data Grid with minimum width to fit content

I am currently working with the MUI Data Grid under an MIT license. My columns are configured as flexible to make use of the available width. However, I want the table to have overflow capabilities for instances where it's resized too small. For ins ...

Merging Two Arrays to Form a Single Array in React

Let's consider the following arrays: const headerArray = ["h1","h2","h3"]; const dataArray=[["a1","a2","a3"],["b1","b2","b3"]]; I have a requirement to merge th ...

Challenges encountered with using TinyMce in Meteor React, specifically when working on iPad devices

I am currently working on an app with Meteor React that uses TinyMce through react-tinymce. I followed the instructions provided at The issue I am encountering is related to a form component with TinyMCE, which allows users to add comments. While it funct ...

Selecting the initial and final elements in a list without utilizing pseudo-classes

Currently, I am in the process of designing a custom MUI styled component and I have encountered a challenge. I want to apply extra styles specifically for the first and last child elements. The issue arises because MUI utilizes the emotion styled library, ...

Utilizing shared references across react-imask, react-bootstrap, and react-hook-form for a seamless integration

I have integrated react-bootstrap and react-imask using their example with IMaskMixin as shown below: import { IMaskMixin } from 'react-imask'; import { FormControl } from 'react-bootstrap'; const MaskedFormControl = IMaskMixin(({input ...

Next.js is causing an error by not recognizing the document variable

While diving into the world of next.js, I encountered an interesting challenge. In my project, I came across this puzzling error. The culprit seemed to be a module called Typed.js, which threw me off with a peculiar message: Server Error ReferenceError: d ...

Retrieving a single object in NEXT.JS and MongoDB can be achieved by returning just a single object

Is there a way to retrieve a single object instead of an array from the API? I am specifically looking for just a single "Event" while using MongoDB and Next.js. Currently, I always receive: [{}] But I would like to receive: {} const fetchWithId = (url ...

Utilize ReactJS to link images with posts

How can we modify the action, reducer, and component to include images for each post in the post list? The current action fetches the post list, but we want to also include the images inside each post. Action export const recipesListFetch = (page = 1) =&g ...

What are the benefits of incorporating an external API with Next.js API routes?

I've recently started using Next.js and I'm curious about the purpose of export default function handler since we can directly fetch data from APIs. In my HTML code, I have the following snippet. When the submit button is clicked, the sendformDa ...

What is the mechanism by which Redux sends state to mapStateToProps?

I'm currently delving into the inner workings of React and Redux, and recently came across FuelSavingsPage.js in this sample project. While I grasp how actions is obtained in mapDispatchToProps, I am uncertain about how state is passed to mapStateToPr ...

Utilize the <wbr> tag within FormattedMessage and assign it as a value while coding with TypeScript

Trying out the optional word break tag <wbr> in a message within <FormattedMessage id="some:message" />. Context Some words or texts are too lengthy for certain parent elements on smaller mobile screens, and we have a column layout t ...

Testing a React component using the `ua-parser-js` plugin with Jest and React Testing Library

I've developed a simple component that displays an image depending on the operating system you are using (in this case, iOS and Android). import { UAParser } from "ua-parser-js"; export const DownloadApp = ({ appleStoreUrl, playStoreUrl }: ...

Ways to trigger an npm script from a higher-level directory?

After separately creating an express-based backend (in folder A) and a react-based front-end project (in folder B), I decided to merge them, placing the front-end project inside the back-end project for several advantages: No longer do I need to manu ...

Passing multiple functions to child components in ReactJS as a single prop

I am utilizing the technique of passing multiple functions as individual props from the parent component to its child components. Everything is working correctly without any errors or problems, but I'm interested in exploring if there is a more effici ...

When is the right time to develop a new component?

Exploring the strategy behind determining when to create a new component in a web application using angularjs / angular has been on my mind lately. It seems like this concept could apply to all component-based front end frameworks as well. I understand th ...

The `.populate()` function is malfunctioning in mongodb

As I work on developing an ecommerce application using Nextjs, one of the challenges I encountered involved populating the "reviewBy" property within an array of objects called "reviews". To tackle this issue, I attempted to populate the "reviewBy" proper ...

Should I consider using an UI framework when initiating a React project?

I'm embarking on a new website project and I'm contemplating whether using a React UI Framework is the way to go, or if I should create my own components and grid system from scratch. I've been drawn to projects like ElementalUI's take ...