Reza Rahgozar
Reza Rahgozar

Reputation: 127

React RTK query Mutation can return value?

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

Upvotes: 10

Views: 9063

Answers (1)

phry
phry

Reputation: 44236

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
       }

    }

Upvotes: 16

Related Questions