Search code examples
ionic-frameworksocket.iolocal-storageionic-storage

How to store the chat messages in to ionic storage?


I created a chat application using ionic and socket.io-client.

In my app when I select a user to begin chat with, my App loads recent chat data from the server then presents it to the user. If there is no network connection, then user cannot see the previous chat messages. so, I want to store the chat messages in to ionic local storage or there is any other better way to store them.

Please kindly advice me a better way to load my recent chat between two users, instead of fetching from the server each time the user is selected.


Solution

  • You already said it, ionic storage is the way to go: https://ionicframework.com/docs/storage/

    For each conversation I would:

    1. Send message to server 
    2. storage.get(conversationID) ....
    3. add message and last message send timestamp to conversation
    4. storage.set(conversationID) ....
    

    When loading messages:

    1. storage.get(conversationID) ....
    2. Check if newer messages are available
    3. If yes -> fetch 
    3.1. add messages and last message send timestamp to conversation
    4. storage.set(conversationID) ....
    

    Always display the local values only and update those when receiving anything. You can also remember object references when sending messages and mark them as not send if any network exception occurs.