我希望你很好,我有一个问题,我正在学习NEXTJS和使用它的api,事实证明,当我点击非常快的承诺得到bug。或者类似的东西,我在这个30秒的短视频中留下了测试和代码演示,希望有人能帮助我,非常感谢。
https://www.youtube.com/embed/K0JTMxpFLQs
------------ CODE ----------
MY REQUEST:
axios.post("/api/reaction", data).then((response) => { return response.data }).then(response => {
if (response.react) {
setNew[key].youLike = true
setNew[key].likes = response.likes
setting(setNew => [...setNew])
} else {
setNew[key].youLike = false
setNew[key].likes = response.likes
setting(setNew => [...setNew])
}
})
我的后端:
export default async function react(req, res) {
let msg, msg_type, react, likes
let { type, id } = req.body
let myId = mySession(req)
if (myId && type && id) {
react = await youLike(myId, id, type)
console.log(react)
if (react) {
await executeQuery({ query: `DELETE FROM cms_likes WHERE owner_id='${myId}' and type='${type}' and post_id='${id}'` })
await executeQuery({ query: `UPDATE cms_posts SET likes=likes-1 WHERE id='${id}' ` })
react = false
} else {
await executeQuery({ query: `INSERT INTO cms_likes (owner_id,type,post_id,time) VALUES ('${myId}','${type}','${id}','${timeNow("s")}') ` })
await executeQuery({ query: `UPDATE cms_posts SET likes=likes+1 WHERE id='${id}' ` })
react = true
}
likes = await executeQuery({ query: `SELECT likes FROM cms_posts WHERE id='${id}'` })
} else {
msg_type = "error"
msg = "!Opps error al enviar tu peticion"
}
res.send({ msg, msg_type, react, likes: likes[0]?.likes })
}
通过多次点击按钮,点赞按钮不能很好地检查它是否存在,并使点赞次数加倍。
存在慢环
slowclick
反应:
0未找到1是的,有0未找到1是的,有0 no found
快速环响应:
反应
2重复2重复0未找到1是的,有0未找到1是的,有0未找到3重复
了解承诺是如何工作的,为了找到解决这个问题的方法,我的帖子将帮助那些可能有同样错误的人。
My connection SQL and FUNCTION EXECUTEQUERY
const db = mysql({
config: {
host: "localhost",
database: "baalbcms",
user: "root",
password: ""
}
})
export default async function executeQuery({ query, values }) {
try {
const results = await db.query(query, values)
await db.end()
return results
} catch (err) {
return err;
}
}
为了使你的SQL更健壮,你应该总是基于likes表计算实际的likes数;事实上,它们不同步是可能的。
我还通过使用values
来修复代码中的SQL注入漏洞。
如果您在单个事务中运行查询,这将更好,但这不能轻易地完成您当前的db
,您在每次查询后end
(您不应该这样做)。
if (react) {
await executeQuery({
query: "DELETE FROM cms_likes WHERE owner_id=? and type=? and post_id=?",
values: [myId, type, id],
});
} else {
await executeQuery({
query: "INSERT INTO cms_likes (owner_id,type,post_id,time) VALUES (?, ?, ?, ?)",
values: [myId, type, id, timeNow("s")],
});
}
await executeQuery({
query: "UPDATE cms_posts SET likes=(SELECT COUNT(*) FROM cms_likes WHERE type=? and post_id=?) WHERE id=?",
values: [type, id, id],
});
likes = await executeQuery({ query: `SELECT likes FROM cms_posts WHERE id=?`, values: [id] });