npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

chatsasa-react-sdk

v1.0.4

Published

A chat SDK for React applications

Downloads

169

Readme

ChatSasa React SDK Documentation

Welcome to the ChatSasa React SDK documentation. This guide will help you get started with integrating the ChatSasa SDK into your React application to enable chat functionalities.

Prerequisites

Before you can start using the ChatSasa SDK, you need to complete the following steps:

1. Sign Up on the ChatSasa Dashboard

  1. Go to the ChatSasa Dashboard and sign up for an account.
  2. Once signed up, log in to your account.

2. Create an Application

  1. Navigate to the "Applications" section in the dashboard.
  2. Click on "Create New Application" and fill in the required details.
  3. Once your application is created, you will be provided with an App ID.

3. Obtain a Chat API Token

  1. The Chat API token is typically obtained from your backend. Ensure your backend integrates with ChatSasa's authentication mechanisms to generate and provide API tokens.
  2. Store the App ID and Chat API Token securely, as these will be used to initialize the SDK.

Installation

To install the ChatSasa SDK, run the following command:

npm install chatsasa-react-sdk

or

yarn add chatsasa-react-sdk

Initialization

Initialize the ChatSasa SDK in your application. Here’s an example of how to do it:

import ChatSasa from "chatsasa-react-sdk";

const chatSDK = new ChatSasa({
  appId: "YOUR_APP_ID",
  chatApiToken: "YOUR_CHAT_API_TOKEN",
});

Usage

Fetching User Profile

To fetch the user profile, use the `fetchUserProfile` method:

chatSDK
  .fetchUserProfile()
  .then((profile) => console.log(profile))
  .catch((err) => console.error(err));

Fetching All Channels

To fetch all channels, use the `fetchAllChannels` method:

chatSDK
  .fetchAllChannels()
  .then(({ channels }) => console.log(channels))
  .catch((err) => console.error(err));

Sending a Message

To send a message, use the `sendMessage` method:

chatSDK
  .sendMessage(channelId, userId, "Hello, World!")
  .then((message) => console.log(message))
  .catch((err) => console.error(err));

Fetching Messages

To fetch messages in a channel, use the `fetchMessages` method:

chatSDK
  .fetchMessages(channelId)
  .then((messages) => console.log(messages))
  .catch((err) => console.error(err));

Deleting a Message

To delete a message, use the `deleteMessage` method:

chatSDK
  .deleteMessage(messageId, channelId)
  .then(() => console.log("Message deleted"))
  .catch((err) => console.error(err));

Marking Message as Read

To mark a message as read, use the `markMessageRead` method:

chatSDK
  .markMessageRead(messageId, channelId)
  .then(() => console.log("Message marked as read"))
  .catch((err) => console.error(err));

Marking Message as Delivered

To mark a message as delivered, use the `markMessageDelivered` method:

chatSDK
  .markMessageDelivered(messageId, channelId)
  .then(() => console.log("Message marked as delivered"))
  .catch((err) => console.error(err));

Fetching Emoji Reactions

To fetch available emoji reactions, use the `fetchEmojiReactions` method:

chatSDK
  .fetchEmojiReactions()
  .then((data) => console.log(data.emojiReactions))
  .catch((err) => console.error(err));

Posting an Emoji Reaction

To post a reaction to a message, use the `postMessageReaction` method:

chatSDK
  .postMessageReaction(messageId, channelId, emojiId, userId)
  .then(() => console.log("Reaction posted"))
  .catch((err) => console.error(err));

Deleting an Emoji Reaction

To delete a reaction from a message, use the `deleteMessageReaction` method:

chatSDK
  .deleteMessageReaction(reactionId, messageId, userId)
  .then(() => console.log("Reaction deleted"))
  .catch((err) => console.error(err));

Fetching Users

To fetch all users, use the `fetchUsers` method:

chatSDK
  .fetchUsers()
  .then((data) => console.log(data.users))
  .catch((err) => console.error(err));

Real-time Events

Connect to Real-time Service

To connect to the real-time service, use the `connect` method:

chatSDK.connect();

Disconnect from Real-time Service

To disconnect from the real-time service, use the `disconnect` method:

chatSDK.disconnect();

Subscribe to Events

To subscribe to real-time events, use the `on` method:

chatSDK.on("new_message", (data) => {
  console.log("New message:", data);
});

chatSDK.on("typing", (data) => {
  console.log("Typing event:", data);
});

chatSDK.on("reaction_created", (data) => {
  console.log("Reaction event:", data);
});

chatSDK.on("message_updated", (data) => {
  console.log("Message update:", data);
});

chatSDK.on("message_delete", (data) => {
  console.log("Message delete:", data);
});

Unsubscribe from Events

To unsubscribe from real-time events, use the `off` method:

chatSDK.off("new_message", callback);
chatSDK.off("typing", callback);
chatSDK.off("reaction_created", callback);
chatSDK.off("message_updated", callback);
chatSDK.off("message_delete", callback);

Example Application

Here is a basic example of how to use the SDK in a React component:

import React, { useEffect, useState } from 'react';
import ChatSasa, { User, Channel, Attachment } from 'chatsasa-react-sdk';

const chatSDK = new ChatSasa({
  appId: 'YOUR_APP_ID',
  chatApiToken: 'YOUR_CHAT_API_TOKEN',
});

function App() {
  const [profile, setProfile] = useState<User | null>(null);
  const [channels, setChannels] = useState<Channel[]>([]);
  const [currentChannel, setCurrentChannel] = useState<Channel | null>(null);
  const [loadingChannels, setLoadingChannels] = useState<boolean>(true);

  useEffect(() => {
    chatSDK.fetchUserProfile()
      .then(profile => setProfile(profile))
      .catch(err => console.error(err));
  }, []);

  useEffect(() => {
    if (profile?.userId) {
      chatSDK.fetchAllChannels()
        .then(({ channels }) => {
          setChannels(channels);
          setLoadingChannels(false);
        })
        .catch(err => console.error(err));
    }
  }, [profile?.userId]);

  useEffect(() => {
    chatSDK.connect();

    const handleNewMessage = ({ channel, message }) => {
      console.log('New message:', channel, message);
    };

    const handleTyping = ({ channel, typingEvent, user }) => {
      console.log('Typing event:', channel, typingEvent, user);
    };

    const handleReaction = ({ channel, reaction }) => {
      console.log('Reaction event:', channel, reaction);
    };

    const handleMessageUpdate = ({ channel, message }) => {
      console.log('Message update:', channel, message);
    };

    const handleMessageDelete = ({ channel, messageId }) => {
      console.log('Message delete:', channel, messageId);
    };

    chatSDK.on('new_message', handleNewMessage);
    chatSDK.on('typing', handleTyping);
    chatSDK.on('reaction_created', handleReaction);
    chatSDK.on('message_update', handleMessageUpdate);
    chatSDK.on('message_delete', handleMessageDelete);

    return () => {
      chatSDK.off('new_message', handleNewMessage);
      chatSDK.off('typing', handleTyping);
      chatSDK.off('reaction_created', handleReaction);
      chatSDK.off('message_update', handleMessageUpdate);
      chatSDK.off('message_delete', handleMessageDelete);
      chatSDK.disconnect();
    };
  }, [profile?.userId]);

  const handleSendMessage = (message: string, attachments: Attachment[]) => {
    if (currentChannel && profile?.userId) {
      chatSDK.sendMessage(currentChannel.channelId, profile.userId, message, attachments)
        .then(({ message }) => {
          setChannels(prevChannels => {
            const updatedChannels = prevChannels.map(channel =>
              channel.channelId === currentChannel.channelId ? {
                ...channel,
                lastMessage: {
                  ...channel.lastMessage,
                  message: message.message,
                  createdAt: message.createdAt,
                },
                unreadMessagesCount: 0, // Reset unread count for the current channel
                 } : channel
            );
            return updatedChannels;
          });
        })
        .catch(err => console.error(err));
    }
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1>Chat Application</h1>
        {loadingChannels ? (
          <p>Loading channels...</p>
        ) : (
          channels.map(channel => (
            <div key={channel.channelId} onClick={() => setCurrentChannel(channel)}>
              {channel.name}
            </div>
          ))
        )}
      </header>
    </div>
  );
}

export default App;

Conclusion

You have successfully set up the ChatSasa SDK in your React application. For more details on available methods and customization options, refer to the official ChatSasa Documentation.

For any issues or further assistance, please contact our support team at [email protected].

Happy Coding!