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?
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--
}
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!
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
})