On my front end, there's a text field where the user types in the email and a button.I am running a graphql query loadUsers()
, which takes the email as an input variable. I am calling it inside my handleSubmit()
.
This returns an id. Then I need to run a mutation createUserRelationMutation
which uses the id.
const [loadUsers, { loading, data, error }] = useLazyQuery(LoadUsersQuery, { variables: { where: { email: friendEmail.toLocaleLowerCase() }, }, onCompleted: ( data: any ) => { console.log('Working'); if (data) { console.log(data); if (data.users.nodes.length == 0) { console.log('No user'); setErrorMessage('User Not Found'); } else { const friendId = data.users.nodes[0].id; console.log('friendId', friendId); const relationParams = { input: { relatedUserId: Number( friendId ), type: RelationType.Friend, userId: 5, // current user? }, } console.log("relation params", relationParams); // fire second query/mutation using received data createUserRelationMutation( { variables: relationParams } ); } } else { if (error) { setErrorMessage(error.message); } } } }); const [ createUserRelationMutation, { data: addingFriendData, loading: addingFriendLoading, error: addingFriendError, }, ] = useCreateUserRelationMutation( { variables: { input: { relatedUserId: Number(id), type: RelationType.Friend, userId: 8, }, }, onCompleted: ( addingFriendData: any ) => { console.log("relation created", addingFriendData); } }); const handleSubmit = () => { loadUsers(); };
<Button onPress={() => handleSubmit()}> Add Friend{''}</Button>
However, once I go to the screen and type something, the loadUsers query automatically starts running. Even before I hit the button. Due to this, the behavior of the mutation isn't correct. How can I fix this?
Before this, when my code was slightly different, the process wasn't working correctly but at least the lazyQuery ran only after the button was clicked. I don't know why it's different now. Reference qs: