-
We know that function App() {
const [searchStr, setSearchStr] = useState('');
const {refetch} = useQuery({
queryKey: ['some-data', searchStr],
queryFn: async () => {},
enabled: false,
onSuccess(data) {
// do something with data
}
})
return <div>
<input value={searchStr} onChange={e => setSearchStr(e.target.value)} />
<button onClick={() => {refetch()}}>trigger fetching when use click button</button>
} in the code above, the user can change In our code, the use case above is rare, but it happens from time to time. how do you guys solve imperative fetching ? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 7 replies
-
i think it's a perfectly valid example for a search form, that, when submitted, should trigger a fetch. The idea is still relatively simple / declarative: only set
here is an example where i'm doing exactly that: https://codesandbox.io/s/react-query-url-filtering-h0ikw?file=/src/App.tsx also, your code will create a (disabled) cache entry for every key stroke, likely not what you want :) |
Beta Was this translation helpful? Give feedback.
-
Hi, I have an additional follow-up question that is related to this. I'm looking to create a more dynamic component that allows for different custom useQuerys' to be passed into the component, and I'm wondering if that is an ok approach, or is there a better alternative. Use cases are for things like Async Select components and Infinite lists. Eg. When a user types in an input, there's a debounce, the For example, the setup I've done that works look something like this, but it doesn't feel right passing hooks down as props, as hooks should not be called conditionally:
Is there a way to approach this better? I'm trying to avoid bloating the codebase with custom individual components like |
Beta Was this translation helpful? Give feedback.
-
Maybe I'm missing the intent of this question, but
That's exactly what I was looking for, myself. (Probably an anti-pattern but I needed it for backwards compatibility with some old code.) |
Beta Was this translation helpful? Give feedback.
i think it's a perfectly valid example for a search form, that, when submitted, should trigger a fetch. The idea is still relatively simple / declarative: only set
searchStr
when the user submits the form. That means you might need some state-duplication, but it's actually good in this example because it is two different states: