简体   繁体   中英

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. The id is not sent in POST but AutoIncremented in the backend. I don't want to navigate to the list-view to get that id but directly.

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),
  • 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.)
  • saving step1 in the localStorage (but then there will be problems with updating previous records),
  • saving step1 in the state (but than I cannot refresh)

It's simple, but only in case your API returns a newly created item on POST response (which is expected for 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:

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"]}`)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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