I'm working in react js and I want to develop notifications component which related to the account related activities. I have to display all the account related activities in the notifications list and sort them as a read
and unread
notifications.
so the my question is how to manage read and unread notification in react/ next js ?
Do I need to make it state or session storage ?
consider this is my notification list :
const notificationArray = [
{ id: 1, msg: 'one' },
{ id: 2, msg: 'two' },
{ id: 3, msg: 'three' },
{ id: 4, msg: 'four' },
{ id: 5, msg: 'five' },
];
And in the below list I have received one new notification :
const notificationArray = [
{ id: 1, msg: 'one' },
{ id: 2, msg: 'two' },
{ id: 3, msg: 'three' },
{ id: 4, msg: 'four' },
{ id: 5, msg: 'five' },
{ id: 6, msg: 'six' }
];
CodePudding user response:
If your notification data comes from database you need to add a new property that indicates weather it is read or no And then you can use just State no need for session whenever the user read the notification you update the list in client side and async tell the back end that the notification has been read
data will look like this:
[{id:1,msg:'msg',read:false}.....]
and client side code will look like this:
const [notifs,setNotifs] = useState()
function setRead(id){
for (var i in notifs) {
if (notifs[i].id === id) {
notifs[i].read = true;
break;
}
}
setNotifs(notifs)
callYourBackEnd(id,readStatus) // here just call your api service or something and send to it id of the notif and the read status 'true of false' which is probably true
}
//maping the notifs list here and pass the id to setRead
notifs?.map(notif=> <NotifComonent onClick={e=>setRead(notif.id)} />
CodePudding user response:
how to manage read and unread notification in react/ next js ?
After creating a new notification, in server-side or client-side, add a property in notification called hasRead
or something, which is by default set to false. Then whenever the user read the notification, set that property to true.
Do I need to make it state or session storage ?
It depends what type of app you are creating. For a real world app, the data probably comes from a database. There are multiple options for storing user data - databases, local storage, session storage, memory. Choose whatever suits your need.
CodePudding user response:
do it like this
const notificationArray = [
{ id: 1, msg: 'one' , read: true },
{ id: 2, msg: 'two' , read: true},
{ id: 3, msg: 'three', read: true },
{ id: 4, msg: 'four' , read: true},
{ id: 5, msg: 'five' , read: true },
{ id: 6, msg: 'six' , read: false }
];
when the message is received you make a notification to the user then you store this data in server or in localStorage