Lifecycle: change data with post request response

Hi!
I’m sending a post request when creating a new entry in the strapi backend. So far, so good. Now I need to manipulate a field with the new data (from the api response) coming in.
module.exports = {

  lifecycles: {

async beforeCreate(data) { 
//send data to an api
//get response from api
//manipulate one of the properties of the data object with the response I got from the post request
//create new product in the strapi backend with the new data
}

}
}

How would I go on about waiting for the data and changing it with the new data I get, BEFORE the actual entry in Strapi gets created?

Thank you so much for any help!

1 Like

You already answered all your questions, I don’t understand where is the problem.


async beforeCreate(data) {

    //send data to an API
    //get response from api
    let externalData = await axios.post('https://some_external_api.com/products', {
        productName: data.name,
        productId: data.id
    });

    //manipulate one of the properties of the data object with the response I got from the post request
    data.price = externalData.data.price;

    //create new product in the strapi backend with the new data
    //--product gets created automatically after executing all the code above--
}

Thank you so much @sunnyson. Yes, that’s exactly what I’ve tried. I’m always getting back the following error:

 error TypeError: Cannot read property 'data' of undefined

So I was wondering if my approach is wrong. Any ideas what could’ve happened?

  let externalData = await axios.post('URL', shopifyProduct, axiosConfig)
  .then((res) => {
console.log("RESPONSE RECEIVED: ", res.status);
console.log("RESPONSE ", res);
  })
  .catch((err) => {
console.log("AXIOS ERROR: ", err);
  })

  data.shopifyID = externalData.data.product.id

POST request works, and I get back the needed response.
Thank you for your help!

//EDIT
Oh nevermind, I just realized my mistake. The data.shopifyID = externalData.data.product.id goes into the Promise and not outside. Thank you so much for your help!

Yeah, also:

When using axios with then and catch, you should manually return the response. In my example I omitted then and catch, Axios in this case returns the response automatically.

 let externalData = await axios.post('URL', shopifyProduct, axiosConfig)
  .then((res) => {
      console.log("RESPONSE RECEIVED: ", res.status);
      console.log("RESPONSE ", res);
      //you've missed the return
      return res // <<<<<<<<< That one. Since you had only console logs there it was not returning any data
  })

Oh, thanks. Changed it now! thanks for your help :slight_smile:

1 Like