import { SuprSend } from "@suprsend/web-sdk";
import { useEffect, useState } from "react";
export default function Example() {
const [feedData, setFeedData] = useState();
const [feedInstance, setFeedInstance] = useState();
const initializeFeed = async (suprSendClient) => {
await suprSendClient.identify("YOUR_DISTINCT_ID"); // authenticating user
const feedClient = suprSendClient.feeds.initialize(); // creating feed instance using suprsend client instance
setFeedInstance(feedClient); // storing it in state so that feed client methods like markRead can be accessed outside
const initialFeedData = feedClient?.data; // get initial store data from feed instance
setFeedData(initialFeedData); // storing that data in react state so that UI is rendered accordingly
feedClient?.emitter.on("feed.store_update", (updatedStoreData) => {
setFeedData(updatedStoreData); // register listener to get updated store data and store it in local react state so that UI is updated w.r.t new state
});
feedClient.initializeSocketConnection(); // register for socketio connection for realtime updated in feed data
feedClient.fetch(); // fetch existing notifications. Once API call is success you get first page notifications in feed.store_update listener and react state update happens which cause UI to renrender.
};
useEffect(() => {
const suprSendClient = new SuprSend("YOUR_PUBLIC_API_KEY"); // creating suprsend client instance
initializeFeed(suprSendClient);
return () => suprSendClient.reset(); // up on unmounting remove user so that inbox data will also be cleared
}, []);
if (!feedData) return null;
if (feedData.apiStatus === "LOADING") return <p>Loading Data</p>;
if (feedData.apiStatus === "SUCCESS" && !feedData?.notifications?.length) {
return <p>No Notifications</p>;
}
if (feedData.notifications) {
return (
<div>
<div>
{feedData.notifications.map((notification) => {
return (
<div
key={notification.n_id}
onClick={() => {
feedInstance.markAsRead(notification.n_id);
}}
>
{notification.n_id}
</div>
);
})}
</div>
{feedData.apiStatus === "FETCHING_MORE" ? (
<p>Loading More</p>
) : (
<div>
{feedData.pageInfo.hasMore && (
<button
onClick={() => {
feedInstance.fetchNextPage();
}}
>
Next
</button>
)}
</div>
)}
</div>
);
}
return null;
}