Reputation: 485
I am using graphql with Apollo for a signup page.
onSubmit
I want to send a query to confirm if the username is unique (currently counting users, I know I should check for exists, but not the scope of this question)
I have several problems doing that.
Using useQuery
sends the Query instantly - I cant choose to send the query on submit.
Using useLazyQuery
sends the Query delayed on calling user_count
.
-> Problem: It is neither a promise nor does onComplete
work (a function that exists in useQuery
and executes once the query finished)
How does useLazyQuery
work? It executes the query. The values are accessible through data_user
which gets updated once the query finishes. data_user
is initally undefined
.
As useLazyQuery
does not return a promise, I decided to create my own promise-like listener.
For what I know the recommended way to do it is a Proxy
. The problem with that is: Trying to set target= data_user
throws
Cannot create proxy with a non-object as target or handler
I could solve it with a setCallback
function that looks every couple MS for a change, but that feels dirty.
export default function Signup() {
const [state, setState] = useState([])
const [user_count, {loading, data: data_user}] = useLazyQuery(USER_COUNT);
const handleSubmit = event => {
event.preventDefault();
const proxy = new Proxy(data_user, {
set: function (target, prop, value) {
if (prop === 'userCount') {
console.log("Query finished")
const user_exists = data_user.userCount !== 0;
console.log(`User exists: ${user_exists}`)
}
}
})
user_count({
variables: {
name: state.value
}
});
Upvotes: 2
Views: 1553
Reputation: 485
I was able to workaround this problem by using useApolloClient
directly:
const client = useApolloClient();
const handleSubmit = event => {
event.preventDefault();
client
.query({
query: USER_COUNT,
variables: {
name: state.value
}
})
.then(response => {
const user_exists = response.data.userCount !== 0;
console.log(`User already exists: ${user_exists}`)
});
}
```
Upvotes: 3
Reputation: 149
You can use the Window Abort controller to cancel the request
Learn more here: https://evilmartians.com/chronicles/aborting-queries-and-mutations-in-react-apollo
at the end of article check the complete example hope it will help you out
Upvotes: 0