Update your code to use the fetch API instead of axios

Looking to switch my axios post call to a fetch 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
}

Trying to convert the above code to use fetch:

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
}

Encountering an issue with the new fetch call: Error in v-on handler (Promise/async): "TypeError: Cannot read property 'id' of undefined. This was not an issue with the axios call. Any idea what could be the problem?

Answer №1

fetch will give you a promise that includes a .json() method which requires you to await it.

Therefore, you should modify return response.data.id to

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

Below is an updated code snippet according to your inquiry:

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
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with APIs surfaced following the transition from DataGridPro to DataGridPremium

In my current project, we initially implemented the MUI X DataGrid but later switched to DataGridPro due to business requirements. Recently, we upgraded our plan from Pro to Premium which has caused some unexpected issues in our existing code. I am using " ...

Looking to identify the type of a adorned class in Typescript?

Consider the following scenario: return function IsDefined(object: any, propertyName: string) { .... ] We then go ahead and decorate a property like this: class Test { @IsDefined() p1: String = ""; } Now, when we execute a test inside the ...

Using Twig: Transfer the content of a textfield as a parameter in the routing

I have a task of redirecting to another page while passing along the value from a textfield. Here is my current code: {% extends "base.html.twig" %} {% block body %} <button onclick="host()">Host the session</button> <button onclic ...

Change the syntax to use async-await

Is it worth converting the syntax to async-await and how can I achieve this? // ---- UserRoutes ---- router.get('/user', middlewareJwt.jwtHandler, function (req, res) { UserService.get(req.userId, (user) => successCbk(res, 200, { ...

Utilizing Vuejs to Modify Laravel Pivot (BelongsToMany) Table

My VueJs form is set up like this, using v-model: <select name="service_id" v-model="client.services[0].pivot.service_id"> <option v-for="service in services" v-bind:key="service.id" v-bind:value=" ...

A Comprehensive Guide on Implementing String Values in Highchart Series

When attempting to pass a string value (data) to the highchart series, I encountered an issue where it would display a blank chart. Is there a specific way to use a string value in the series of the highchart jQuery plugin? var data="{name: 'Jane&apo ...

Ways to update the div's appearance depending on the current website's domain

There is a piece of code that is shared between two websites, referred to as www.firstsite.com and www.secondsite.com The goal is to conceal a specific div only when the user is on secondsite. The access to the HTML is limited, but there is an option to ...

I'm having trouble getting jQuery to work properly with Bootstrap buttons

In simple terms, my objective is to have two buttons on a page where "1" is displayed when the first button is pressed and "2" is displayed when the second button is pressed. This functionality works fine with radio inputs, but when I incorporate button la ...

The MDX blog was set up to showcase markdown content by simply displaying it without rendering, thanks to the utilization of the MDXProvider from @mdx-js/react within Next JS

I'm currently in the process of setting up a blog using MDX and Next.js, but I've encountered an issue with rendering Markdown content. The blog post seems to only display the markdown content as plain text instead of rendering it properly. If y ...

Top method for preventing an HTTP 403 error when receiving the Set-Cookie header in order to establish the CSRF Cookie

As I interact with a REST API that includes CSRF protection measures, I am facing a common hurdle. Successfully obtaining the token and sending it back to the server seems to work smoothly. However, encountering an HTTP 403 error arises when initiating t ...

Error message "Legacy application encounters issue with Vue web component due to object extensibility constraint"

I am facing an issue with importing my custom component in an older app. I pre-compiled my Single File Component (SFC) as a web component using the vue-cli builder, and then imported it into my main.js file like this: import * as HelloWorld from '../d ...

When attempting to install Vue Js, I encounter the following npm error

I recently set up Node.js using Snap on my Parrot OS system. However, I've noticed that the node_modules folder is missing after /usr/local/lib When running npm install -g @vue/cli, I encountered this error: npm WARN deprecated @hapi/[email pro ...

Cease animation if the page has already reached its destination

In my current setup, I am using a JavaScript code snippet to navigate users to the specific location of the information they click on in a side navigation menu. However, one issue that arises is if they first click on one item and then another quickly, t ...

How to retrieve an anchor element from a list using JavaScript

My current code loops through each <li> within a <td> cell and adds a class to the <li>. I have now inserted <a> tags between each <li> and am facing challenges in accessing the <a> tags. What I actually want is to assig ...

Guide to Generating Downloadable Links for JPG Images Stored in MongoDB Using Node.js

I have successfully uploaded an image to MongoDB as a Buffer. Now, I need to figure out how to display this image in my React Native app using a URL, for example: http://localhost:8080/fullImg.jpeg How can I achieve this? Below is the MongoDB Schema I am ...

Deselect a checkbox that is already selected and choose the current option in the multiselect dropdown

I've created a code that allows for single select in a multiselect dropdown, disabling other options once one is chosen. However, I don't want to disable the checkboxes and would like to uncheck the selected option if a new one is chosen, all whi ...

Show a concealed dropdown menu within a CSS grid column utilizing clip-path styling

Working on a Django admin header that makes use of CSS grid to create two columns. I have added a JavaScript dropdown effect to the user icon for displaying options like "Change Password" and "Log Out". However, encountering an issue where the dropdown rem ...

Is there a method to obtain specific props for focused tabBar badges to customize the background color accordingly?

Is there a way to specify focused props in tabBarBadgeStyle to customize the background color? options={{ tabBarLabel: "Teams", tabBarBadge: '3', tabBarBadgeStyle: { backgroundColor: ORANGE ...

The ng-model does not reflect changes when using the JQuery datepicker

Currently, I have set up two textboxes for users to choose a date. I am utilizing JqQuery's datepicker UI to showcase a small calendar pop-up whenever the user clicks on the textbox. However, an issue arises when I select a date in the calendar popup ...

The removeEventListener method in JavaScript fails to function properly

On my website, I have a unique feature where clicking an image will display it in a lightbox. Upon the second click, the mouse movement is tracked to move the image accordingly. This functionality is working as intended, but now I'm faced with the cha ...