Fetch API in Javascript
Fetch() is a function in Javascript. It runs on all the latest browsers. The fetch API allows browsers to make HTTP requests to web servers to get, put, post, and delete data.
Overview
let promise = fetch(url)
- A promise is returned
- url is the webserver endpoint
http://www.example
Example
fetch('https://jsonplaceholder.typicode.com/todos/1
.then(res => res.json())
.then(json => console.log(json)
Optional Parameters
let promise = fetch(url, [params])
- params is optional. params is where the parameters such as the header and methods depending on the webserver API.
- JSON format is used most of the time in the parameters and in the body.
const params = {
method='get'
headers = {
Authorization: ‘Bearer + token'
Content-Type: 'application/json'
Body: JSON.stringify(data)
}
Dad Joke Examples
function generateJoke() {
const config = {
headers: {
'Accept':'application/json'
}
}
fetch('https://icanhazdadjoke.com', config)
.then((res) => res.json())
.then((data) => {
jokeText.innerHTML = data.joke
}
}
Async Await with fetch
Since fetch uses a promise and is asynchronous, you can simplify the code using Async / Await syntax:
async function generateDadJoke () {
const res = await fetch('https://icanhazdadjoke.com',config)
const data = await res.json()
jokeText.innerHTML = data.joke
}
json() is also an asynchronous function and needs to use Await.
Fetch Limit
One of the limits of fetch is that the API’s can be written without a maximum number of records that can be retrieved. This can cause a lot of network traffic issues and possibly hang up the application.
Tip: use filter and splice to better handle your data.
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => res.json())
.then((data) =>
{
data = data.filter(entry => entry.created > someValue)
.slice(0, 1000);
// Limit to 1000
// ...use data... })
.catch(error => {
// <=== handle errors
// Handle error... })
}
TheMovieDB.org Example
TheMovieDB.org handles the number of records passed using parameters that are passed in the url.
Construct the url with different parameters to limit and sort the data.
- api key
- page
- desc/ asc
https://api.themoviedb.org/3/movie/popular?api_key=<<api_key>>&language=en-US&page=1
AXIOS Limits
AXIOS, which comes in the NPM package and is used for ReactJS is a popular way to retrieve data. It has parameters that allow a limit.
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/todos',{
params: {
_limit: 10
}
})
.then((res) => {
this.setState({
todos: res.data
});
})
}
Try / Catch
Handling errors using fetch is really important. An easy way to handle the errors is to wrap them in a try-catch block.
try {
fetch()
} catch( error => {
console.error(“There was a problem with your fetch: ”, error)
}
Or
let response = fetch()
if (!response.ok) {
const message = `An error has occured: ${response.status}`;
throw new Error(message)
}
SUMMARY
The function fetch() makes a request. It returns a promise. When the request completes, the promise resolves to the response object. Then it’s easy to extract the data in the format that you need such as JSON or raw text.
Thank you for reading the article. Keep on coding and growing.
-Richard Soriano