3.0.1 • Published 5 months ago

@engagespot/react-hooks v3.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

Engagespot React Hooks

@engagespot/react-hooks is a collection of React hooks that provide seamless integration with Engagespot's notification services. Built on top of @engagespot/store and @engagespot/core, these hooks allow you to easily add real-time notifications, web push, and user preference management to your React applications.

Table of Contents

Features

  • Easy Integration: Quickly add notification features to your React apps.
  • Notification Feed: Manage and display notification lists with pagination.
  • Real-Time Updates: Receive notifications in real-time without manual polling.
  • Web Push Support: Subscribe users to web push notifications effortlessly.
  • User Preferences: Allow users to manage their notification preferences.
  • UnSeen Counts: Keep track of unread notifications and display badges.
  • Actions: Perform actions like mark as read, delete notifications, etc.

Installation

Install the package using npm or yarn:

# Using npm
npm install @engagespot/react-hooks

# Using yarn
yarn add @engagespot/react-hooks

Note: react is a peer dependency and should be installed in your project.

Getting Started

Before you begin, ensure you have your Engagespot API Key and have set up your Engagespot account. Visit the Engagespot Dashboard to obtain your API key.

Usage Examples

Initializing the Provider

Wrap your application with the EngagespotProvider to make the hooks available throughout your component tree.

import React from 'react';
import { EngagespotProvider } from '@engagespot/react-hooks';

function App() {
  return (
    <EngagespotProvider
      options={{
        apiKey: 'YOUR_ENGAGESPOT_API_KEY',
        userId: 'unique_user_identifier',
        userSignature: 'optional_user_signature', // If using HMAC authentication
        debug: true, // Optional: Enable debug mode
        itemsPerPage: 20, // Optional: Number of notifications per page
      }}
    >
      {/* Rest of your app */}
    </EngagespotProvider>
  );
}

export default App;

Using the Notification Feed

Use the useFeed hook to access and display notifications.

import React from 'react';
import { useFeed } from '@engagespot/react-hooks';

function NotificationList() {
  const { notifications, loading, loadMore, hasMore } = useFeed();

  if (loading) return <div>Loading...</div>;

  return (
    <div>
      {notifications.map(notification => (
        <div key={notification.id}>
          <h4>{notification.title}</h4>
          <p>{notification.message}</p>
        </div>
      ))}
      {hasMore && <button onClick={loadMore}>Load More</button>}
    </div>
  );
}

export default NotificationList;

Handling Unseen Counts

Use the useUnseenCount hook to get the number of unseen notifications.

import React from 'react';
import { useUnseenCount } from '@engagespot/react-hooks';

function NotificationBadge() {
  const unseenCount = useUnseenCount();

  return (
    <div>
      <span>Notifications</span>
      {unseenCount > 0 && <span>({unseenCount})</span>}
    </div>
  );
}

export default NotificationBadge;

Web Push Notifications

Use the useWebPush hook to manage web push subscriptions.

import React from 'react';
import { useWebPush } from '@engagespot/react-hooks';

function WebPushButton() {
  const { subscribe, webPushState, isSupported } = useWebPush();

  const handleSubscribe = async () => {
    if (isSupported()) {
      await subscribe();
    } else {
      alert('Web Push is not supported in this browser.');
    }
  };

  return (
    <button onClick={handleSubscribe} disabled={webPushState === 'granted'}>
      {webPushState === 'granted' ? 'Subscribed' : 'Enable Notifications'}
    </button>
  );
}

export default WebPushButton;

Managing User Preferences

Use the usePreferences hook to access and update user preferences.

import React from 'react';
import { usePreferences } from '@engagespot/react-hooks';

function Preferences() {
  const { preferences, setPreferences } = usePreferences();

  const handleToggle = (categoryId, channelId, enabled) => {
    const updatedPreferences = preferences.categories.map(category => {
      if (category.id === categoryId) {
        return {
          ...category,
          channels: category.channels.map(channel =>
            channel.id === channelId
              ? { ...channel, enabled: !enabled }
              : channel,
          ),
        };
      }
      return category;
    });

    setPreferences(
      updatedPreferences.map(category => ({
        categoryId: category.id,
        channels: category.channels.map(channel => ({
          channel: channel.id,
          enabled: channel.enabled,
        })),
      })),
    );
  };

  return (
    <div>
      {preferences.categories.map(category => (
        <div key={category.id}>
          <h4>{category.name}</h4>
          {category.channels.map(channel => (
            <label key={channel.id}>
              <input
                type="checkbox"
                checked={channel.enabled}
                onChange={() =>
                  handleToggle(category.id, channel.id, channel.enabled)
                }
              />
              {channel.name}
            </label>
          ))}
        </div>
      ))}
    </div>
  );
}

export default Preferences;

Performing Actions

Use the useActions hook to perform actions like marking notifications as read.

import React from 'react';
import { useFeed, useActions } from '@engagespot/react-hooks';

function NotificationList() {
  const { notifications } = useFeed();
  const { markAsRead, deleteNotification } = useActions();

  const handleMarkAsRead = id => {
    markAsRead(id);
  };

  const handleDelete = id => {
    deleteNotification(id);
  };

  return (
    <div>
      {notifications.map(notification => (
        <div key={notification.id}>
          <h4>{notification.title}</h4>
          <p>{notification.message}</p>
          <button onClick={() => handleMarkAsRead(notification.id)}>
            Mark as Read
          </button>
          <button onClick={() => handleDelete(notification.id)}>Delete</button>
        </div>
      ))}
    </div>
  );
}

export default NotificationList;

API Reference

EngagespotProvider

The EngagespotProvider component should wrap your application to provide context for the hooks.

Props

  • options (StoreOptions): Configuration options for the Engagespot store.

Example

<EngagespotProvider options={{ apiKey: 'your-api-key', userId: 'user-id' }}>
  {/* Your app components */}
</EngagespotProvider>

Hooks

useFeed()

Access the notification feed.

Returns

  • notifications: Array of notifications.
  • loading: Boolean indicating if notifications are being loaded.
  • loadMore(): Function to load the next page of notifications.
  • refresh(): Function to refresh the notification list.
  • hasMore: Boolean indicating if more notifications are available.

useUnseenCount()

Get the number of unseen notifications.

Returns

  • unseenCount: Number of unseen notifications.

useWebPush()

Manage web push notifications.

Returns

  • subscribe(): Function to subscribe to web push notifications.
  • clearWebPushSubscription(): Function to unsubscribe from web push.
  • isSupported(): Function to check if web push is supported.
  • webPushState: Current web push permission state.

usePreferences()

Access and update user preferences.

Returns

  • preferences: User preferences object.
  • setPreferences(preferences): Function to update preferences.
  • setProfileAttributes(attributes): Function to set user profile attributes.
  • channels: Available notification channels.

useActions()

Perform actions on notifications.

Returns

  • markAsRead(notificationId): Mark a notification as read.
  • deleteNotification(notificationId): Delete a notification.
  • markAllAsRead(): Mark all notifications as read.
  • deleteAllNotifications(): Delete all notifications.
  • markAsSeen(): Mark notifications as seen.
  • changeState({ id, state }): Change the state of a notification.

useEvent(eventName, callback)

Listen to real-time events.

Parameters

  • eventName (string): Name of the event to listen to.
  • callback (function): Callback function to execute when the event occurs.

Example

useEvent('notificationReceive', data => {
  console.log('New notification received:', data);
});

Contributing

We welcome contributions to the Engagespot React Hooks! If you have ideas, suggestions, or issues, please open an issue or pull request on our GitHub repository.

Development Setup

Clone the repository:

git clone https://github.com/Engagespot/engagespot-react-hooks.git

Install dependencies:

cd engagespot-react-hooks
npm install

Run tests:

npm test

Build the project:

npm run build

Coding Guidelines

  • Follow the existing code style and structure.
  • Write unit tests for new features or bug fixes.
  • Ensure all tests pass before submitting a pull request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

For more information about Engagespot and its features, please visit our official website or check out our documentation.

If you have any questions or need assistance, feel free to reach out to our support team at support@engagespot.co.

1.4.2

12 months ago

1.4.1

12 months ago

1.4.0

12 months ago

3.0.1

5 months ago

3.0.0

8 months ago

2.1.0

1 year ago

2.0.0

1 year ago

1.3.8

1 year ago

1.3.7

2 years ago

1.3.6

2 years ago

1.3.5

2 years ago

1.3.4

2 years ago

1.3.3

2 years ago

1.3.2

2 years ago

1.3.1

2 years ago

1.3.0

2 years ago

1.1.9

2 years ago

1.1.8

3 years ago

1.1.7

3 years ago

1.1.6

3 years ago

1.1.5

3 years ago

1.1.1

3 years ago

1.0.2

3 years ago

1.1.0

3 years ago

1.1.4

3 years ago

1.1.3

3 years ago

1.1.2

3 years ago

1.0.3-alpha.0

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago

0.1.11

3 years ago

0.1.12-alpha.1

3 years ago

0.1.12-alpha.2

3 years ago

0.1.1-alpha.8

4 years ago

0.1.1-alpha.9

4 years ago

0.1.1-alpha.11

4 years ago

0.1.1-alpha.10

4 years ago

0.1.1

4 years ago

0.1.1-alpha.4

4 years ago

0.1.1-alpha.60

4 years ago

0.1.1-alpha.5

4 years ago

0.1.8

4 years ago

0.1.7

4 years ago

0.1.1-alpha.17

4 years ago

0.1.4

4 years ago

0.1.1-alpha.15

4 years ago

0.1.1-alpha.59

4 years ago

0.1.3

4 years ago

0.1.1-alpha.14

4 years ago

0.1.1-alpha.13

4 years ago

0.1.1-alpha.3

4 years ago

0.1.1-alpha.2

4 years ago