There's a text field where the user types in the email and a button. For now, I am trying to use a hardcoded email value. I am running a graphql query loadUsers()
, which takes the email as an input variable.
This query returns an id. Then I need to run a mutation createUserRelationMutation
which uses the id.
const [friendEmail, setFriendEmail] = useState('ana@hotmail.com'); const [errorMessage, setErrorMessage] = useState(''); 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); // setId(data.users.nodes[0].id); const relationParams = { input: { relatedUserId: Number( friendId ), type: RelationType.Friend, userId: 8, // 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); } });
<Input placeholder="Email" //onChangeText={(text) => setFriendEmail(text)} value={friendEmail} /><Button onPress={()=>loadUsers()}><Text style={scaledAddFriendEmailStyles.text}> Add Friend{''}</Text></Button>
However, with this method, it only works the first time I click on the button. Nothing happens if I click on it again.
If I remove the hardcoded email value and uncomment the onChange in the input field, in that case the query starts running before I submit the button. The query keeps running while I am typing or erasing something from the text field. How can I fix this?
My original code & issue was a bit different. Reference qs:proper use of onCompleted for GraphQL mutations