简体   繁体   English

如何在 RTK 查询中的 POST 后导航到更新/详细信息页面

[英]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?最好的解决方案是什么?

  • try to send the id in response from the backend after POST (Django Rest Framework),尝试在 POST(Django Rest Framework)之后从后端发送 id 作为响应,
  • change the primary key in the backend as such that I will know the id before handleSubmit (did that before but forgot the reason why I set everything back.)更改后端中的主键,这样我就会知道 handleSubmit 之前的 id(之前做过但忘记了我将所有内容都设置回来的原因。)
  • saving step1 in the localStorage (but then there will be problems with updating previous records),将 step1 保存在 localStorage 中(但是更新之前的记录会有问题),
  • saving step1 in the state (but than I cannot refresh)将 step1 保存在 state 中(但我无法刷新)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM