How to get previous component data in lifecycle hook

System Information
  • Strapi Version: 4.5.0
  • Operating System: MacOS
  • Database: sqlite/postgres
  • Node Version: v16.14.0
  • NPM Version: 8.3.1
  • Yarn Version: 1.22.17

Does anyone know how to get previous component data for a collection-type in lifecycle hook in strapi v4 before the component data gets updated? Because the event.params.data will return a useless object like this for a component, which doesn’t give me the component data I need

[
  {
     id: 44,
     __pivot: {
     field: 'kickoutFlag',
     component_type: 'outcome-component.kickout-flag'
     }
   }
]

I tried getting the previous component data using 4 different methods in the beforeUpdate lifecycle hook, but in all 4 cases it returns me the updated component data rather than the previous component data before it gets updated. I listed the 4 methods I used and attached a screenshot of what I tried.
My collection-type is called tass and my component is called kickoutFlag just for some context.
Please can anyone tell me how I can get previous component data before it is updated in a lifecycle hook?

  1. strapi.requestContext.get();
  2. Using entityService api
  3. using strapi.query
  4. using strapi.db.query

In my opinion: You can’t.

In v3 this was possible.

In v4 you need to fetch the data before performing the update.

We wrapped update & delete in our own “secureUpdate” / “secureDelete” methods and perform a findOne there before we do the update.

Thanks for that info. Would you be able to share in a code snippet or maybe screenshot how you wrap your update in your own “secureUpdate” method before doing the update?

v4 does not returns the currently stored relational data inside event object. It only sends the changes in the relational data using connect(array of ids added) and disconnect(array of ids removed). To get the current data you need to query DB.

const { data, where, select, populate } = event.params;
const id = where.id;
const existingData = await strapi.entityService.findOne("api::name.name", id, {
        populate: ["relationalField1", "relationalField2"],
      })
1 Like