--- type: slide slideOptions: display: block --- # ACIT 1620 ## Week 12 --- <!-- .slide: data-transition="zoom convex-out" style="text-align: left"--> Objectives: - Fetch API - Local Storage --- <!-- .slide: data-transition="zoom convex-out" style="text-align: left" --> # Fetch API - Allows making HTTP requests programmatically - No page reloads - Often used to access data from a variety of data endpoints, including RESTful web services - **Asynchronous**, i.e. returns a promise - Generally uses JSON --- ### REST (REpresentational State Transfer) - Exposes networked resources represented as URIs - Accessed using HTTP protocols Examples: - `/users` : a collection of users - `/users/1`: a single user - `/users/1/posts`: blog posts belonging to a particular user ---- ## HTTP methods/ verbs - GET: for retrieving resources - POST: for creating a resource - PUT: for fully updating an existing resource - PATCH: for partially updating an existing resource - DELETE: for deleting a resource --- # Examples Schema (blog post): ```javascript { title: '', body: '', } ``` ## Retrieving resources ```javascript fetch("/posts") .then(response => response.json()) .then(data => { // use data console.log(data); }) .catch(error => console.error(error)); ``` ---- ## Creating a resource ```javascript fetch("/posts", { method: 'POST', headers: { 'Content-type': 'application/json', }, body: JSON.stringify({ title: 'My title', body: 'post body', }), }) .then(response => response.json()) .then(data => { // use data -> the newly created resource console.log(data); }) .catch(error => console.error(error)); ``` ---- ## Updating a resouce ```javascript fetch("/posts/1", { method: 'PUT', headers: { 'Content-type': 'application/json', }, body: JSON.stringify({ id: 1, title: 'New title', body: 'new post body' }), }) .then(response => response.json()) .then(data => { // use data -> the updated resource console.log(data); }).catch(error => console.error(error)); ``` ---- ## Deleting a resource ```javascript fetch("/posts/1", { method: 'DELETE', }) .then(response => { if (response.ok) console.log('Deleted!') }) .catch(error => console.error(error)); ``` ---- ## Using async/await ```javascript async function getPosts() { try { const response = await fetch("/posts"); const data = await response.json(); // use data console.log(data) } catch(error) { console.error(error); } } getPosts(); ``` --- <!-- .slide: data-transition="zoom convex-out" style="text-align: left" --> # Local Storage - part of Web Storage API - two varieties: `localStorage` and `sessionStorage` - `sessionStorage` lets you store data on the client for a single session (until the browser or tab is closed) - `localStorage` lets you store data on the client that persists until explicitly deleted. --- # Origin - Local storage APIs create a storage area per origin - origin to the part of a URL that includes the `protocol` or scheme, the `hostname` and `port`. - Eg: `https://example.com` - Both `https://example.com/sales/` and `https://example.com/products` share the same origin - ...but not `https://sales.example.com` --- <!-- .slide: data-transition="zoom convex-out" style="text-align: left" --> - use `localStorage.getItem(item)` to retrieve an item from storage. Returns null if the item does not exist - use `localStorage.setItem(item, value)` to store an item in storage - `localStorage` can only store strings (both keys and values) ---- - `localStorage` can only store string objects - To store complex data structures, you need to first convert them to a string representation using JSON - `JSON.stringify(obj)`: converts an object to a string representation in JSON format - `JSON.parse(JSON_string)`: converts a JSON object into a javascript object ---- - Take the following object for example: ``` const person = { name: 'John Doe', age: 35 }; ``` You can store it like so: ``` localStorage.setItem('john', JSON.stringify(person)); ``` You can retrieve it like so: ``` const person = JSON.parse(localStorage.getItem('john')); ```