How to get the response data by using react-query useMutation and axios post method?

1.8k views Asked by At

I'm trying to get the data from a axios post methed. I can get it by only using axios. I cannot figure out why using the react-query useMutation console log the response data is undefined.

api/index.js

export const postCreateMeetingId = async (token) => {
    await axios.post('http://localhost:3001/create-meeting/', {token:`${token}`}, {
        headers: {
           "Content-Type": "application/json",
            authorization: `${token}`,
        },
    })
    .then((res) => {
        console.log(res.data) //successfully got the data here
        return res.data
    })
}

pages/meetingRoom.js

var token='my token is here'
export default function MeetingRoom(){
    const {mutate, data} = useMutation(postCreateMeetingId, {
        onSuccess: async (res) => {
            console.log(res) //undefined
            console.log(data) //undefined
        }
    })
    const getMeetingAndToken = async () => {
        return mutate(token)
    }

    return(
        <div>
            <button onClick={getMeetingAndToken}>get</button>
        </div>
    );
}

I wish to know how to get the response data by using useMutation so that I could throw this data to another post api.

1

There are 1 answers

0
TkDodo On BEST ANSWER

postCreateMeetingId is not returning anything. You create a Promise with axios.post, and you await it, but you're not returning it. The mix of async / await and .then() in the function unnecessarily complicates things:

export const postCreateMeetingId = (token) => {
    return axios.post('http://localhost:3001/create-meeting/', {token:`${token}`}, {
        headers: {
           "Content-Type": "application/json",
            authorization: `${token}`,
        },
    })
}