Home » vue » Migrate axios to fetch

Migrate axios to fetch

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have an axios post call:

export async function createFriend ({
  let myData = new FormData()
  myData.append('name', name)
  myData.append('age', age)
  const response = await axios.post('/myApi/friends', myData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  return response.data.id
}

I want to migrate this to a fetch call:

export async function createFriend ({
  let myData = new FormData()
  myData.append('name', name)
  myData.append('age', age)

  const response = await fetch('/myApi/friends', {
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data: myData
  })
  return response.data.id
}

However i’m getting the following error: Error in v-on handler (Promise/async): "TypeError: Cannot read property ‘id’ of undefined. But this didnt happen in the axios call. What am I doing wrong?

Answers:

fetch returns a promise that has a .json() method which you need to await.

So you need to change return response.data.id to return (await response.json()).id;

Here is a full code sample from your question with the fix applied:

export async function createFriend ({
  let myData = new FormData()
  myData.append('name', name)
  myData.append('age', age)

  const response = await fetch('/myApi/friends', {
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data: myData
  })

  return (await response.json()).id
}