Fetch API
Fetch API is used to make server request. The return value is a Promise. This allows us to build simple and clean API calls.
Basic Fetch Request
Example to use Fetch to get data from server
1 | fetch("https://jsonplaceholder.typicode.com/todos/1" ) |
output
1 | { |
fetch()
method takes a url as the first argument. The return value is a Promise. json()
method converts the response to json. It is the most used method.
POST Request
The fetch()
method call accepts a second optional parameter. You specify the request options such as method, headers and body using the second parameter.
Example to send a POST message with headers and body.
1 | fetch('https://jsonplaceholder.typicode.com/posts', { |
output
1 | { |
Async and await
You can rewrite the fetch request using async/await. This sometimes makes the code easier to understand and maintain. no more .then()
chains.
Async function that uses fetch() to make http request
1 | async function getTodo() { |
1 | async function createPost() { |
await
blocks execution of the code that follows until the promise fulfills. So you need to be careful when using async/await