[英]How to navigate to the update/detail page after a POST in RTK query
I've got a form with a POST in REACT RTK-query and then it should navigate to the second step, but for that I need to know the id of the newly created record.我在 REACT RTK 查询中有一个带有 POST 的表单,然后它应该导航到第二步,但为此我需要知道新创建记录的 ID。 The id is not sent in POST but AutoIncremented in the backend.
id 不是在 POST 中发送的,而是在后端自动递增的。 I don't want to navigate to the list-view to get that id but directly.
我不想直接导航到列表视图来获取该 id。
const [addMyModel] = useNewMyModelMutation();
const handleSubmit = (e: { preventDefault: () => void; }) => {
e.preventDefault();
const my_model = {
"user_id": user_id,
"date_time_field": new Date(),
"icm": icmChoice,
...
};
dispatch(setUniqueFilters(unique_filters))
//localStorage.setItem('unique_filters', JSON.stringify(unique_filters))
//localStorage.setItem('selection_positions', JSON.stringify(positions))
//localStorage.setItem('my_model', JSON.stringify(my_model))
addMyModel(my_model)
push(`/icm/mymodels/list`) // push(`/icm/mymodels/${answer_question}`);
What could be the best solution?最好的解决方案是什么?
It's simple, but only in case your API returns a newly created item on POST response (which is expected for RESTfull API).这很简单,但前提是您的 API 在 POST 响应中返回新创建的项目(这是 RESTfull API 所期望的)。 If so - just await the answer from hook:
如果是这样 - 只需等待钩子的回答:
const data = await addMyModel(my_model).unwrap()
// id should be in `data`
Considering that mutation "trigger" function returns a Promise, you can use it as usual:考虑到突变“触发器”function 返回 Promise,您可以像往常一样使用它:
addMyModel(my_model).then(newItem => {
if ("data" in newItem) {
const expectedId = item.data.id;
// use you expectedId
}
});
const [addMyModel, result] = useNewMyModelMutation();
...
const handleSubmit = (e: any) => {
e.preventDefault();
const my_model = {
"user_id": user_id,
"date_time_field": new Date(),
"icm": icmChoice,
...
};
addMyModel(my_model)}
result.status === "fulfilled" && push(`/icm/mymodels/update/step2/${result.data["id"]}`)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.