React RTK query Mutation can return value?
Asked Answered
A

1

10

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);

Arvo answered 1/8, 2022 at 9:2 Comment(2)
for any example to make sense you need to show how you are calling the mutation in your codeMulligan
Hi Phry , Thank you for your comment , I already added more detail to my question . many thanksArvo
M
14

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
       }

    }
Mulligan answered 1/8, 2022 at 13:39 Comment(5)
Interesting. How come we in your answer don't use data as described in the docs redux-toolkit.js.org/rtk-query/usage/…? Why not somthing like this? const [addRecord, { data: data }] = useAddRecordMutation()Haydenhaydn
@Haydenhaydn 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?Mulligan
Yes, true I noticed this behaviour as I was coding.Haydenhaydn
and how about 'error' is of type 'unknown'.Lorenelorens
@AmirRezvani caught errors in TypeScript are always unknown, since you can't really know what they are before closely looking at them. An error could be caused by anything and vary wildly in content.Mulligan

© 2022 - 2024 — McMap. All rights reserved.