A reminder for functional programming in javascript.
Also, here is a good short comparison of functional and object-oriented programming.
https://www.baeldung.com/cs/oop-vs-functional
ES6 Fetch API
Fetch API intro
This allows us to perform declarative HTTP requests to a server. For each request, it creates a Promise
which must be resolved in order to define the content type and access the data.
The fetch()
method returns a Promise
that resolves the Response
from the Request
to show the status (successful or not). If you ever get this message promise {}
in your console log screen, don’t panic — it basically means that the Promise
works, but is waiting to be resolved. So in order to resolve it we need the .then()
handler (callback) to access the content.
So in short, we first define the path (Fetch), secondly request data from the server (Request), thirdly define the content type (Body) and last but not least, we access the data (Response).
From Mozilla docs:
WindowOrWorkerGlobalScope
is implemented by both Window
and WorkerGlobalScope
, which means that the fetch()
method is available in pretty much any context in which you might want to fetch resources.
// Basic blueprint fetch(url) .then(response.something) // Define response type (JSON, Headers, Status codes) .then(data) // get the response type // Practical example fetch('https://jsonplaceholder.typicode.com/users/1') .then(response => response.json()) .then(data => console.log(data))
CRUD and other HTTP request methods
HTTP defines a set of request methods to indicate the desired action to be performed for a given resource. Although they can also be nouns, these request methods are sometimes referred to as HTTP verbs. Each of them implements a different semantic.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
Main methods are:
- POST (create a new resource)
- GET
- DELETE
- PUT (update resource – replaces all representations of current resource)
- PATCH (partially update resource)
Other methods include HEAD, CONNECT, OPTIONS, TRACE
Creating a new user
// Create a new user fetch('https://jsonplaceholder.typicode.com/users', { headers: { "Content-Type": "application/json; charset=utf-8" }, method: 'POST', body: JSON.stringify({ username: 'Elon Musk', email: 'elonmusk@gmail.com', }) })
Deleting a user
// Create a new user // we have to use the URL specific to that user (...users/1) fetch('https://jsonplaceholder.typicode.com/users/1', { method: 'DELETE' })
Updating a user
// Update user with id 3 fetch('https://jsonplaceholder.typicode.com/users/3', { headers: { "Content-Type": "application/json; charset=utf-8" }, method: 'PUT', body: JSON.stringify({ username: 'Elon Musk', email: 'elonmusk@gmail.com', }) })