Skip to content

Instantly share code, notes, and snippets.

@obymanyando
Created August 23, 2021 12:26
Show Gist options
  • Save obymanyando/dd8652dbabcd478fb5935df56a5133cc to your computer and use it in GitHub Desktop.
Save obymanyando/dd8652dbabcd478fb5935df56a5133cc to your computer and use it in GitHub Desktop.
Little JS Snippets
// Making API call
// Fetch API
fetch('http://example.com/huha.json')
.then(response => response.json())
.then(data => console.log(data));
// Example: Get languages from the countries API
const API_URL = 'https://restcountries.eu/rest/v2/all'
fetch(API_URL)
.then((response) => response.json())
.then((data) => {
const langs = []
for (const country of data) {
let { languages } = country
for (const lang of languages) {
langs.push(lang.name)
}
}
console.log(langs)
console.log(`Languages of the world:, ${langs.length}`)
})
//...............................................................................
// Axios
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
})
.catch(function (error) {
// handle error
})
.then(function () {
// always executed
});
// Use with params
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
// handle success
})
.catch(function (error) {
// handle error
})
.then(function () {
// always executed
});
// use async/await
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment