Trying to get my head around fetching data only once, thought useQuery works like useEffect
See original GitHub issueWhen using useQuery I’ve noticed that if I change some state on my component, the query gets rerun as one would expect.
function Index() {
...
const [dialogOpen, setDialogOpen] = useState({ show: false, id: '0' });
...
const { data, error } = useQuery(GET_JOBS, { suspend: true });
if (error) {
return <div>Error! {error.message}</div>;
}
const jobs = data.cxJobs; //This is our data
....
function editCallback(e, more) {
setDialogOpen({ show: true, id: e });
}
....
}
Since I only want it to happen the first time it renders, I assumed it worked like useffect, and that by adding an empty array to the end of the call:
const { data, error } = useQuery(GET_JOBS, { suspend: true }, []);
It turns out that’s the not the case. Plus it seems to me there’s no easy way to make that happen with useQuery. You can’t call a hook conditionally.
Do I need to fallback to using the client directly?
Issue Analytics
- State:
- Created 4 years ago
- Reactions:5
- Comments:6
Top Results From Across the Web
getting error when I run useQuery inside the useEffect hook in ...
As mentioned in the other answer, you can only call hooks at the top level in the body of a functional component/custom hook....
Read more >Fetching Data in React with useEffect - Max Rozen
Fetching data from an API, communicating with a database, and sending logs to a logging service are all considered side-effects, as it's possible...
Read more >Understanding common frustrations with React Hooks
React Hooks can be frustrating despite their popularity and widespread use. Learn about some of the drawbacks to using React Hooks.
Read more >React Query - A practical example. - DEV Community
If you want to fetch data to be used in the app, it can be done very easily. React Query provides us the...
Read more >React Query 3: A Guide to Fetching and Managing Data
Head over to your browser and open http://localhost:3000 to access the application. You should have an identical experience as shown in the ......
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
You could do something like this. Also, you might also want to avoid setting the result of the query to useState and just use data directly.
What if the same query is being used at two different components and I want it to fetch only once and serve it from cache in the other component?