2

I'm using react native and apollo client for an app that creates a chat given an array of selected users. My code looks like this:

        const [addUser, {
    data: userAdded, loading: addingUsers, error: errorAddingUsers,
  }] = useMutation(ADDUSERTOCHAT)

  const [makeChat, {
    data: chat, loading: chatLoading, error: chatError,
  }] = useMutation(NEWCHAT, {
    variables: { ownerId: viewerId },
    onCompleted: () => {
      for (let i = 0; i < selectedFriends.length; i++) {
        addUser({
          variables: {
            chatId: chat.newChat.id,
            id: selectedFriends[i].id,
          },
          onCompleted: () => {
            if (i === selectedFriends.length - 1) {
              navigation.navigate('Chat', { chatId: chat.newChat.id })
            }
          },
        })
      }
    },
  })

Right now, this does not work. I am not sure how to run the addUser mutation only after the chat is created, and I'm also not sure if the for loop will work to run a mutation for every selected friend. I also need to navigate to the screen chat once everything in the process is done and I'm not sure if the condition I have will work for that. In sum, I'm a bit lost with how to sequence these mutations and can't get it to work. Any help is appreciated thanks!

jchm
  • 83
  • 1
  • 4
  • In your NEWCHAT mutation, I don't think the variables you are destructuring exist (```chat``` ```chatLoading``` ```chatError```). You would need to [destructure and rename them](https://stackoverflow.com/questions/57065348/destructuring-and-rename-property) to use different variable names than the default (data, loading, error). The logic for executing ```addUser``` after ```makeChat``` seems correct, but synchronously making a series of asynchronous calls can cause issues. It would be better to have one mutation which accepts an array of ID's to mutate. – Chris B. May 19 '22 at 06:45
  • Great catch, thanks! I think it should work with the edit now? And yeah, the mutation which accepts an array makes sense. – jchm May 19 '22 at 06:53
  • Actually I missed that you are calling the ```makeChat``` mutation in the function. Since it's asynchronous, you would need to move all of the ```addUser``` functionality inside your ```onCompleted``` callback, otherwise there is no guarantee the mutation has completed and set ```chatCreated``` to true. – Chris B. May 19 '22 at 06:58
  • Thanks!! What about the latest edit then? – jchm May 19 '22 at 07:01

0 Answers0