Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper Way to Make API Fetch 'POST' with Async/Await

I'm working on a project that requires me to make requests to an API. What is the proper form for making a POST request with Async/Await?

As an example, here is my fetch to get a list of all devices. How would I go about changing this request to POST to create a new device? I understand I would have to add a header with a data body.

getDevices = async () => {   const location = window.location.hostname;   const response = await fetch(     `http://${location}:9000/api/sensors/`   );   const data = await response.json();   if (response.status !== 200) throw Error(data.message);   return data; }; 
like image 871
Nik Ackermann Avatar asked Apr 26 '18 15:04

Nik Ackermann


People also ask

How do I use async await to fetch data from API?

Using async/awaitYou start by specifying the caller function as async and then use await to handle the promise. Because of the await keyword, the asynchronous function pauses until the promise is resolved. The Response object is assigned to response once the request completes.

Does fetch support async await?

Fetch using async/await syntaxFunctions are prepended by the keyword async , which enables the use of the keyword await inside them. Any process that returns a promise is prepended by the keyword await , which halts execution of the code below it until the promise is resolved or rejected.

How do I convert fetch to async await?

Because fetch() returns a promise, you can simplify the code by using the async/await syntax: response = await fetch() . You've found out how to use fetch() accompanied with async/await to fetch JSON data, handle fetching errors, cancel a request, perform parallel requests.


1 Answers

actually your code can be improved like this:

to do a post just add the method on the settings of the fetch call.

getDevices = async () => {     const location = window.location.hostname;     const settings = {         method: 'POST',         headers: {             Accept: 'application/json',             'Content-Type': 'application/json',         }     };     try {         const fetchResponse = await fetch(`http://${location}:9000/api/sensors/`, settings);         const data = await fetchResponse.json();         return data;     } catch (e) {         return e;     }      } 
like image 130
Prince Hernandez Avatar answered Sep 18 '22 21:09

Prince Hernandez