I have a query that takes input params, say date
const { loading, data, error } = useQuery(GET_LIST, {
variables: {
input: {
date: date,
},
},
});
export const GET_LIST = gql`
query list($input: ListParams) {
list(input: $input) {
totalCount
recordCount
list {
listId
date
qty
amount
currency
}
}
}
`;
input ListParams {
date: String
}
I need to fetch the list, where the user can filter based on date. Now on initial load, date is not set, query is called. The user sets a date, no issues, the query is called again with the the date value, now when the user removes the date filter, the date value becomes undefined, and I would expect useQuery to be called again with no variables this time, but it is never called.
I have tried setting empty string as well, even then useQuery does not get called which is not the intended behaviour
input: {
date: date||'',
},
Apollo-Cilent has a cache mechanism when query variable you pass into the useQuery hook is the same to a previous value.
Doc: https://www.apollographql.com/docs/react/data/queries/ Sandbox: https://codesandbox.io/embed/usequery-example-apollo-client3-dx626
You can solve this by either using a refetch or polling mechanism built into the useQuery hook:
function Date({ date }) {
const { loading, data, error, refetch } = useQuery(GET_LIST, {
variables: {
input: {
date: date,
},
},
});
//...
return (<div>
<Component data={data} onDateChange={() => refetch()}/>
</div>)
}
Or, if having the empty/undefined variable in the query doesn't specific purpose, you should probably not render the component by adding {!input.date && <Date /> } or not sending any query by adding skip variable in your useQuery hook:
const { loading, data, error, refetch } = useQuery(GET_LIST, {
variables: {
input: {
date: date,
},
},
skip: !input?.date // <------ Skip the query when input.date is missing or empty
});
Late answer (I think you have probably resolved this issue), I am writing some notes here in case someone else runs into this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With