React-Query: callback after setQueryData

Viewed 151

In a form, upon receiving a response from server, I update the cache using setQueryData. However, after the cache update, I want to trigger the form input field to be focused again.

Details:

In my React app, I am using Recoil.js to manage the state. React-Query is used to fetch & cache the data. I normalise the data & store in Recoil state, to which the React components subscribe for update.

While React-Query's setQueryData is a synchronous function, however, the app refresh because of new data is not (& any call after the setQueryData is not actioned).

How can I trigger the form input focus after the refresh of cache?

1 Answers

you can just call the focus function right after you call setQueryData, as it's synchronous:

setQueryData(key, newData)
focusField() //some function that focuses the field

alternatively, you can spawn a useEffect that always does something when data updates:

const { data } = useQuery(...)

useEffect(() => {
  focusField()
}, [data])
Related