How do I get my useQuery() to fire on both first render as well as on subsequent events (e.g. button click)?
From what I've read, when React mounts a component that calls a useQuery for the first time, Apollo automatically executes the query, and if I want to execute that query in response to an event, I can instead use useLazyQuery which returns a function that can be called. What if I want to do both?
Not very sure which part of my understanding of React hooks is incorrect or incomplete, but I've tried with using refetch in useQuery, which definitely allows me to call that function, but doesn't seem to always fire upon component mount (the more confusing thing is that sometimes it does, sometimes it doesn't). I'm also using notifyOnNetworkStatusChange, which I read it needed for refetch to recognise that it should trigger the onCompleted part of the useQuery.
Any help would be much appreciated, I think I don't really understand Hooks at all. Thanks!
P.S. an example of my useQuery is as follows:
const { refetch: refetchGetTaskTypes } = useQuery(GET_TASK_TYPES(["taskId", "taskType"]), {
notifyOnNetworkStatusChange: true,
onCompleted: (data) => {
if (data !== undefined && data.getTaskTypes !== undefined && data.getTaskTypes !== state.taskTypes) {
dispatch({
type: 'GET_TASK_TYPES',
payload: {
taskTypes: data.getTaskTypes
}
});
}
}
});
P.P.S. as an example of refetch sometimes needing to be called to render and other times not, I have another useQuery that is almost identical to the above (with a different query) that also has refetch, but it renders on first load
P.P.P.S. I sometimes see another issue where refetch gets outdated data, and I have to use fetchPolicy: 'cache-and-network' to fix it. It doesn't always happen however