我有一个带有Sequelize/mysql的react/node/express应用程序。使用AXIOS进行API调用。
-
将配方发布到数据库
-
等待上述操作完成
-
再次获取配方表以使用新配方更新反应组件状态
-
配方被发布到数据库
-
获取配方在
诺言从岗位上收回。因此,组件状态得到
设置为旧数据。
以下是简略代码:
addRecipe: async function(newRecipe) {
let addRecipe = await axios.post('/api/recipes/new', newRecipe)
return addRecipe
},
getRecipes: function() {
return axios.get('/api/recipes');
}
食谱.js:
import API from '../../utils/API';
state = {
dbRecipes: []
}
getRecipes = () => {
API.getRecipes()
.then(res => {
this.setState({
dbRecipes: res.data
})
})
}
handleFormSubmit = event => {
event.preventDefault();
API.addRecipe(formData).then(result => {
this.getRecipes()
})
}
添加配方控制器:
exports.addRecipe = function (req, res) {
const imgPath = req.file.path.replace('client/public','');
db.Recipe.create({
RecipeName: req.body.RecipeName,
RecipeDescription: req.body.RecipeDescription,
RecipeImage: imgPath
}).then(function (newRecipe) {
RecipeIngredients = JSON.parse(req.body.RecipeIngredients)
var promises = [];
for (var i = 0; i < RecipeIngredients.length; i++) {
var RecipeId = newRecipe.dataValues.id;
promises.push(
db.RecipeAmount.create({
Amount: RecipeIngredients[i].AmountForSmall,
Size: 'sm',
Type: 'smoothie',
IngredientId: RecipeIngredients[i].IngredientId,
RecipeId: RecipeId
})
);
promises.push(
db.RecipeAmount.create({
Amount: RecipeIngredients[i].AmountForMedium,
Size: 'md',
Type: 'smoothie',
IngredientId: RecipeIngredients[i].IngredientId,
RecipeId: RecipeId
})
);
promises.push(
db.RecipeAmount.create({
Amount: RecipeIngredients[i].AmountForLarge,
Size: 'lg',
Type: 'smoothie',
IngredientId: RecipeIngredients[i].IngredientId,
RecipeId: RecipeId
})
);
}
sequelize.Promise.all(promises).then(function () {
//this does get logged out in the backend console
console.log('DONE ADDING');
});
});
};