Sharing state between beforeDelete and afterDelete lifecycle hooks

System Information
  • Strapi Version: 4.0.2
  • Operating System: Ubuntu v21.10
  • Database: SQLite
  • Node Version: 16.13.1
  • Yarn Version: 3.1.1

Hello,

I am trying to use lifecycle hooks to delete all localizations of a collection type item when the default localization is deleted.

I couldn’t access to the localizations objects in the afterDelete, but I found a workaround by fetching the item in beforeDelete with localizations populated:

strapi.db.lifecycles.subscribe({
  async beforeDelete(event) {
    const id = event.params.where.id;
    const item = await strapi.entityService.findOne(event.model.uid, id, {
      populate: { localizations: true },
    });
  },
});

But I don’t want to delete items in the beforeDelete hook because I don’t want to delete items if the default locale deletion fails.

In the Hook event object documentation, there is a word about the state property of the event object:

Query state, can be used to share state between beforeXXX and afterXXX events of a query.

So I tried to assign event.state in the beforeDelete hook:

event.state = { item }

But I in the event object received by the afterDelete lifecycle hook, the state property is undefined.

Is it possible to add some data to the event object to share it between beforeDelete and afterDelete lifecycle hooks?

1 Like

did you find solution? What i can see in V4 hooks there is no state property to share data between hooks, I made temp field in collection type to send data to afterDelete hook.

I didn’t find a clean solution. What you did can work as a workaround, but this is not very clean. The documentation tells that there should be a way to share data between before and after lifecycle hooks. So there is two possibilities:

  • either the v4 documentation is not accurate on this point
  • or there is an issue with the event.state property in v4
1 Like

I would say probably both, documentation is not up to date as they are still updating.

Did anyone find a cleaner solution to this? Or get any response from Strapi? I’m hitting this issue as well :frowning:

Nothing on my side :confused:

I’m facing the same problem.
According to the documentation, I should be able to share a state between hooks.