useNovu

Learn how to use the useNovu hook to access the Novu client instance in your React Native application

The useNovu hook provides access to the Novu client instance from anywhere in your React Native application. This hook must be used within a component that is wrapped by the NovuProvider.

Return Value

type NovuReturn = {
  novu: Novu;
  isLoading: boolean;
  error: Error | null;
};

Example Usage

Here's how to use the useNovu hook to interact with the Novu client:

import { useNovu } from '@novu/react-native';
import { View, Button, ActivityIndicator } from 'react-native';
 
function NotificationActions() {
  const { novu, isLoading } = useNovu();
 
  if (isLoading) return <ActivityIndicator />;
 
  const markAllAsRead = async () => {
    await novu.notifications.readAll();
  };
 
  const archiveAllRead = async () => {
    await novu.notifications.archiveAllRead();
  };
 
  return (
    <View>
      <Button title="Mark All as Read" onPress={markAllAsRead} />
      <Button title="Archive All Read" onPress={archiveAllRead} />
    </View>
  );
}

Accessing Notification Methods

The Novu client provides methods for managing notifications:

import { View, Text, Button } from 'react-native';
 
function NotificationItem({ notification }) {
  const { novu } = useNovu();
 
  const markAsRead = async () => {
    await novu.notifications.read(notification.id);
  };
 
  const archive = async () => {
    await novu.notifications.archive(notification.id);
  };
 
  return (
    <View>
      <Text>{notification.content}</Text>
      <Button title="Mark as Read" onPress={markAsRead} />
      <Button title="Archive" onPress={archive} />
    </View>
  );
}

Managing Preferences

You can also manage notification preferences:

import { Button } from 'react-native';
 
function PreferencesManager() {
  const { novu } = useNovu();
 
  const updatePreferences = async () => {
    await novu.preferences.update({
      workflowId: 'workflow_id',
      channelPreferences: {
        email: false,
        sms: true,
      },
    });
  };
 
  return <Button title="Update Preferences" onPress={updatePreferences} />;
}

The Novu client instance provides access to all the functionality available in the Headless API.

import { useNovu } from '@novu/react-native';
 
const NotificationToast = () => {
  const novu = useNovu();
 
  useEffect(() => {
    const listener = ({ result: notification }) => {
      // Show a toast notification
    };
 
    novu.on('notifications.notification_received', listener);
 
    return () => {
      novu.off('notifications.notification_received', listener);
    };
  }, [novu]);
 
  return null;
};

On this page