useNotifications
Learn how to use the useNotifications hook to fetch and manage notifications in your React Native application
The useNotifications
hook provides a way to fetch and manage notifications in your React Native application. It includes support for pagination, and filtering.
Hook Parameters
Parameter | Type | Required | Description |
---|---|---|---|
storeId | string | No | Filter notifications by a specific store ID |
query | object | No | Additional query parameters for filtering |
Return Value
type NotificationReturn = {
notifications: {
id: string;
content: string;
createdAt: Date;
read: boolean;
seen: boolean;
// ... other notification fields
}[];
hasMore: boolean;
isLoading: boolean;
error: Error | null;
loadMore: () => void;
refetch: () => void;
};
Example Usage
Here's how to use the useNotifications
hook to fetch and display notifications:
import { useNotifications } from '@novu/react-native';
import { View, Text, ActivityIndicator, FlatList } from 'react-native';
function NotificationsList() {
const { notifications, hasMore, isLoading, error, loadMore } = useNotifications();
if (isLoading) return <ActivityIndicator />;
if (error) return <Text>Error: {error.message}</Text>;
return (
<FlatList
data={notifications}
keyExtractor={(item) => item.id}
renderItem={({ item: notification }) => (
<View>
<Text>{notification.content}</Text>
<Text>{new Date(notification.createdAt).toLocaleString()}</Text>
<Text>{notification.read ? 'Read' : 'Unread'}</Text>
</View>
)}
onEndReached={hasMore ? loadMore : undefined}
onEndReachedThreshold={0.5}
ListFooterComponent={hasMore ? <ActivityIndicator /> : null}
/>
);
}
With Pull to Refresh
You can implement pull-to-refresh using the refetch
function:
import { useNotifications } from '@novu/react-native';
import { RefreshControl, FlatList, View, Text, ActivityIndicator } from 'react-native';
function RefreshableNotificationsList() {
const { notifications, isLoading, refetch } = useNotifications();
return (
<FlatList
data={notifications}
keyExtractor={(item) => item.id}
renderItem={({ item: notification }) => (
<View>
<Text>{notification.content}</Text>
<Text>{new Date(notification.createdAt).toLocaleString()}</Text>
</View>
)}
refreshControl={<RefreshControl refreshing={isLoading} onRefresh={refetch} />}
/>
);
}
With Filters
You can apply filters using the query parameter:
import { RefreshControl, FlatList, View, Text, ActivityIndicator } from 'react-native';
function FilteredNotifications() {
const { notifications, isLoading } = useNotifications({
query: {
templates: ['welcome-template', 'order-update'],
emails: ['user@example.com'],
},
});
if (isLoading) return <ActivityIndicator />;
return (
<FlatList
data={notifications}
keyExtractor={(item) => item.id}
renderItem={({ item: notification }) => (
<View>
<Text>{notification.content}</Text>
</View>
)}
/>
);
}