Do lifecycle hooks work with components?

Hello,

I have a product content type with variations component like this:

product{ id name slug SKU images { url } brands { name slug } collections { name slug } variations { id sku images{ url } style color size amount price sale } description sold published_at }
I want to sync the fields SKU between a product and its variations, for example, once input the parent SKU (XXXX), the child SKUs are created as XXXX-1, XXXX-2, etc…

Thanks

Components themselves do not have lifecycles but your product content-type will, within the lifecycle you can use the strapi.query('product').whateverAction() to find/findOne/Update/ect and do the relative sync there as well.

2 Likes

Thanks I just made it.

@lodisy can you share how did you solve your problem?

2 Likes

I did it the following way, which feels a likte hacky (essentially @DMehaffy 's suggetion with more details).

I.e. to update a value you could do the following:

// src/api/[content-type]/content-types/[content-type]/lifecycles.js
let product = await strapi.query('componentGroup.component').findOne({where: {id: event.params.data.Component.id}});
strapi.query('componentGroup.component').update({
      where: {id: product.id},
      data: {
          field1: foo(course.field1)
      }
})

All database operations can be found here:
https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/query-engine/single-operations.html#create