Instead of retrieving a whole webpage once, ajax allows us to retrieve individual data items from the server to update sections of a webpage without having to load an entire new page.
This led to the creation of technologies that allow web pages to request small chunks of data using APIs like XMLHttpRequest or โ nowadays โ the Fetch API.
Fetch does not retrieve the data immediately. It takes some time for the request to reach the server, and for it to respond with the requested data. Therefore, a mechanism exists to indicate that you want to execute code only after you have obtained the answer to the request.
A basic fetch request
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
- calculate the url to be queried, which we then switch to fetch
- wait for data response (async) & then resolve it as json
- then take data & do something with the data obtained
const fetchGitHubProfileJSON = () => {
const username = 'AnneQuinkenstein';
const url = `https://api.github.com/users/${username}`;
fetch(url)
.then((res)=> res.json())
.then((profile) => {
const profileHtml = `
<p><strong>${profile.name}</strong></p>
<img src="${profile.avatar_url}" />
`;
document.querySelector('#github-profile').innerHTML = profileHtml;
});
fetchGitHubProfileJSON();
Axios
Advantages comparing to fetch: the automatic transformation of JavaScript objects into JSON and vice versa & better error management mechanisms
$ yarn add axios
axios
const fetchPokemonJSON =()=> {
const pokemonId = 1;
const url = `https://pokeapi.co/api/v2/pokemon/${pokemonId}`;
axios.get(url)
.then(res => res.data)
.then(pokemon => {
console.log('data decoded from JSON:', pokemon);
const pokemonHtml = `
<p><strong>${pokemon.name}</strong></p>
<img src="${pokemon.sprites.front_shiny}" />
`;
document.querySelector('#pokemon').innerHTML = pokemonHtml;
});
}
fetchPokemonJSON();
GitHub for first Example
API with React
Get Data from the API & store it in App's state.
The "parent" component will make the API calls, and pass the received information to the "child" component(s).
axios with React
Top comments (0)