8

Is is possible to get the response of endpoint in React RTK Query Mutation . I have a one mutation which insert into DB and I need to get the ID which inserted. in my api :

addRecord: build.mutation({
        query(data) {
            return {
                url: base + 'myControler/SaveDataAsync',
                method: 'post',
                data: data,
            }
        },
    }),

and in my component after import my hook I call it like

const [addRecord] = useAddRecordMutation();

and then in my submit function is use it like

    const handleSubmitCustom = async (values) => {

       await addRecord(values);

    }

which I need the return value of await addRecord(values);

Reza Rahgozar
  • 99
  • 1
  • 7

1 Answers1

12

You can just do

    const handleSubmitCustom = async (values) => {

       try {
          const returned = await addRecord(values).unwrap();
       } catch (error) {
         // you can handle errors here if you want to
       }

    }
phry
  • 35,762
  • 5
  • 67
  • 81
  • Interesting. How come we in your answer don't use `data` as described in the docs https://redux-toolkit.js.org/rtk-query/usage/mutations#frequently-used-mutation-hook-return-values? Why not somthing like this? `const [addRecord, { data: data }] = useAddRecordMutation()` – saner Jul 06 '23 at 01:38
  • 1
    @saner That would become available as a new variable called `data` during the next render, but you want to immediately continue working with it in the same closure, right? – phry Jul 06 '23 at 06:47
  • Yes, true I noticed this behaviour as I was coding. – saner Jul 09 '23 at 20:34