How to use hooks for showing total number of notification in header section?

here is start/hooks.js,

const {hooks} = require('@adonisjs/ignitor')
const Notification = use('App/Models/Notification');

hooks.before.providersBooted( () => {
    const View = use('Adonis/Src/View')

    Notification.find().sort({_id : -1}).then(function(result) {
        View.global('notifications', function () {
            return result;
        })
    })

    
})

Hare is header.edge,

<span class="badge badge-default"> {{ size(notifications()) }}</span>

Problem is notification number not change when page is refresh or new record inserted .
Please help me from getting out of this.

Yeah, because providers are booted only once and hence the value is also computed once.

Also, I do see that the query you are running is incorrect. find().sort() isn’t a method anywhere mentioned in the docs

I too face the same problem.

I want to display data in the left hand side menu on every page (which is included in every view) and would like to know that also.

Then what should I do for change the value continuously when new data inserted .

find().sort({})

It’s a Mongo DB query. I fetch the total result set from notification.

Let’s try to understand the situation properly.

1. You want to refetch the count on every request?
If yes, then ignitor hooks isn’t the right way to go, since it is executed only once and you must use middleware for that.

class NotificationsCounter {
   async handle ({ view }, next) {
      const result = await Notification.find().sort({ _id: 1 })
      view.share({ notifications: result })

      await next()
   }
}
1 Like

Problem is solved.
Thank you very much.