Skip to content

Instantly share code, notes, and snippets.

@barangerbenjamin
Created January 14, 2021 21:42
Show Gist options
  • Save barangerbenjamin/e09978a3aab6e760b7bfd8ca9c86b2fe to your computer and use it in GitHub Desktop.
Save barangerbenjamin/e09978a3aab6e760b7bfd8ca9c86b2fe to your computer and use it in GitHub Desktop.
const form = document.getElementById('new-car'); // Retrieve the form and store it in a variable
form.addEventListener('submit', (event) => { // Listen for a form submit
event.preventDefault(); // prevent the page to reload
const car = { // create a car object that we can feed later to the API
brand: document.getElementById('brand').value, // retrieve the brand from the form input
model: document.getElementById('model').value, // retrieve the model from the form input
plate: document.getElementById('plate').value, // retrieve the plate from the form input
owner: document.getElementById('owner').value // retrieve the owner from the form input
}
const url = "https://wagon-garage-api.herokuapp.com/batch-476/cars"; // define the API url
fetch(url, { // start the HTTP query towards the APi using fetch
method: 'POST', // specify the verb of the HTTP query, post is to send informations to the API
headers: {'Content-Type': 'application/json'}, // specify what content we're sending
body: JSON.stringify(car) // when we receive data from API, we parse with json, when we send data we stringify with json
})
.then(response => response.json()) // parse response from API with json
.then((data) => {
displayCar(data); // send api response (the car created) to be displayed
});
});
const displayCar = (result) => { // create function to display cars
const cars = document.querySelector('.cars-list'); // retrieve HTML element in which we're going to add cars
const car = `<div class="car">
<div class="car-image">
<img src="http://loremflickr.com/280/280/${result.brand} ${result.model}" />
</div>
<div class="car-info">
<h4>${result.brand} ${result.model}</h4>
<p><strong>Owner:</strong>${result.owner}</p>
<p><strong>Plate:</strong>${result.plate}</p>
</div>
</div>`; // build car HTML element
cars.insertAdjacentHTML('beforeend', car); // add car HTML element before the end of the cars HTML element
}
fetch("https://wagon-garage-api.herokuapp.com/batch-476/cars") // // start the HTTP query towards the APi using fetch
.then(response => response.json()) // parse response from API with json
.then((data) => {
data.forEach((result) => { // iterate over all the cars present in the garage
displayCar(result); // send car to be displayed
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment