Your database structure should be as follows
- Data Type called ‘Conversation’ with fields called ‘Participants’ which is a list of Users
- Data Type called ‘Message’ with a field called ‘Conversation’ (related to data type called Conversation), field for ‘Content’ (whatever is the text message)
With that simple setup you can find all Conversation any User is part of by constraining on the Participants list. You can find any Message sent by any User by filtering on the ‘Created By’ built in field. You can find ALL Messages in a Conversation by searching Messages and constraining by Conversation.
Then in your Repeating Group, you will have the datasource set to Messages and the Search will be for Messages with a Constraint of ‘Conversation’ is equal to…NOW the equal to part is the selected Conversation, which to make the Chat functionality a Fully Realized feature, you NEED to anticipate use case examples of when you will inevitably need to Show a specific Conversation based on a selection from another area of the app or even an email or phone alert, so our Selected Conversation should be a URL parameter (search the forum for URL parameters, you’ll find enough posts I’ve put up with details on how to understand and use them if you do not already).
So your Message Repeating Group will show from the database all Messages whose conversation is equal to the conversation in the URL parameter.
Then on the left side for list of all conversations you will have repeating group set to data type of Conversation with a search for Conversation with a constraint of ‘Participants’ contains Current User.
Then in that Repeating Group have the elements to show the details.
Then whatever elements you put into the Repeating Group for conversation, when you click you need to set the Conversation, and you do that by running the workflow action of ‘go to page’ and you will go to the same page your chat is on, and add parameter for ‘conversation’ to be equal to the ‘current cells conversation unique ID’.
DO NOT bother to try and create this with Custom States. Use URL Parameters for the selected conversation.
You should be either using the bubble database for storing these or using the API call responses, not both, and which you choose is dependent on the use case of the chat function. If it is chatbot for support, you can just use the API response and perhaps if your use case requires, save to DB at end. If this is chat between people to return to, then store in DB first as soon as AI response is provided, and if saved properly it will immediately appear in the RG for messages after saving to the DB.
There are other more efficient ways to do this, but they are more advanced.