mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-06-19 21:09:51 +08:00
feat(curriculum): add localstorage lecture transcripts (#57629)
This commit is contained in:
parent
76b7dceae1
commit
38bf95ec6e
@ -1,14 +1,92 @@
|
||||
---
|
||||
id: 6733ab64775d35f78f5238fe
|
||||
title: What Does CRUD Stand For, and How Do the Basic Operations Work?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
challengeType: 19
|
||||
# videoId: nVAaxZ34khk
|
||||
dashedName: what-does-crud-stand-for-and-how-do-the-basic-operations-work
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the video lecture and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
CRUD is an acronym that stands for Create, Read, Update, and Delete. These are the four operations of persistent storage.
|
||||
|
||||
Persistent storage refers to saving data in a way that makes it available even after the power is turned off or the device is restarted.
|
||||
|
||||
Understanding how the basic operation of CRUD works is crucial to web development because it forms the foundation for working with databases and building applications where users can add, view, modify, and delete data.
|
||||
|
||||
Now, let’s take a look at each part of CRUD more closely
|
||||
|
||||
- Create refers to the process of creating new data. For example, in a web app, this could be when a user adds a new post to a blog.
|
||||
|
||||
- Read is the operation where data is retrieved from a database. For instance, when you visit a blog post or view your profile on a website, you’re performing a read operation to fetch and display data stored in the database.
|
||||
|
||||
- Update involves modifying existing data in the database. An example would be editing a blog post or updating your profile information.
|
||||
|
||||
- Delete is the operation that removes data from a database. For instance, when you delete a blog post or account, you’re performing a delete operation.
|
||||
|
||||
CRUD is used when working with databases, the UI, and RESTful APIs. RESTful APIs are a set of conventions for building web services that allow the client to interact with a database or backend system by performing CRUD operations through standard HTTP methods.
|
||||
|
||||
HTTP stands for Hypertext Transfer Protocol and it is the foundation for data communication on the web. There are HTTP methods which define the actions that can be performed on resources over the web. The common methods are `GET`, `POST`, `PUT`, `PATCH`, `DELETE`.
|
||||
|
||||
You will learn more about RESTful APIs and HTTP in future videos, but here is a quick break down of how CRUD maps to the different HTTP methods.
|
||||
|
||||
- `POST` is used to create a new resource.
|
||||
|
||||
- `GET` is used to retrieve or read data.
|
||||
|
||||
- `PUT` is used to update a resource by replacing it entirely.
|
||||
|
||||
- `PATCH` is used to partially update a resource.
|
||||
|
||||
- `DELETE` is used to remove a resource.
|
||||
|
||||
Here’s an example of how CRUD operations might be represented in code using a simple array in JavaScript:
|
||||
|
||||
```js
|
||||
let items = [];
|
||||
|
||||
// Create
|
||||
function createItem(item) {
|
||||
items.push(item);
|
||||
}
|
||||
|
||||
// Read
|
||||
function readItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
// Update
|
||||
function updateItem(index, newItem) {
|
||||
items[index] = newItem;
|
||||
}
|
||||
|
||||
// Delete
|
||||
function deleteItem(index) {
|
||||
items.splice(index, 1);
|
||||
}
|
||||
|
||||
// Example Usage
|
||||
createItem('Book');
|
||||
console.log(readItems()); // ['Book']
|
||||
updateItem(0, 'Magazine');
|
||||
console.log(readItems()); // ['Magazine']
|
||||
deleteItem(0);
|
||||
console.log(readItems()); // []
|
||||
```
|
||||
|
||||
In this example:
|
||||
|
||||
- We create an item by pushing it into an array.
|
||||
|
||||
- We read the items by returning the array.
|
||||
|
||||
- We update an item by modifying the array element at a given index.
|
||||
|
||||
- We delete an item by removing it from the array using splice().
|
||||
|
||||
This is a basic representation of how CRUD operations work at a conceptual level.
|
||||
|
||||
# --questions--
|
||||
|
||||
|
||||
@ -1,14 +1,80 @@
|
||||
---
|
||||
id: 6733ff4a9319c8486750886c
|
||||
title: What Is localStorage, and What Are Some Common Methods?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
challengeType: 19
|
||||
# videoId: nVAaxZ34khk
|
||||
dashedName: what-is-localstorage-and-what-are-some-common-methods
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the lecture video and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
The Web Storage API provides a mechanism for browsers to store key-value pairs right within the browser, allowing developers to store information that can be used across different page reloads and sessions.
|
||||
|
||||
The two main components in the Web Storage API are `localStorage` and `sessionStorage`.
|
||||
|
||||
`localStorage` is the part of the Web Storage API that allows data to persist even after the browser window is closed or the page is refreshed. This data remains available until it is explicitly removed by the application or the user.
|
||||
|
||||
`sessionStorage` is another part of the Web Storage API that stores data for the duration of the page session, meaning the data is available as long as the browser tab or window is open. However, unlike `localStorage`, the data in `sessionStorage` is cleared when the tab or window is closed. You will learn more about `sessionStorage` in the next video.
|
||||
|
||||
Common use cases for `localStorage` include storing user settings, such as themes or language preferences, remembering form data across browser sessions, and caching small pieces of information to improve the performance of web apps.
|
||||
|
||||
Caching refers to storing frequently accessed data in a temporary storage location, known as a cache, so that subsequent requests for that data can be served more quickly without having to recompute or fetch it from a slower data source, such as a database or external server.
|
||||
|
||||
Some common `localStorage` methods include the `setItem`, `getItem`, `removeItem` and `clear` methods.
|
||||
|
||||
Here is an example of using the `setItem()` method which stores a key-value pair in `localStorage`.
|
||||
|
||||
```js
|
||||
localStorage.setItem('username', 'JaneDoe');
|
||||
```
|
||||
|
||||
Then if we want retrieve that value of a given key from `localStorage`, we can use the `getItem()` method.
|
||||
|
||||
```js
|
||||
let username = localStorage.getItem('username');
|
||||
console.log(username); // JaneDoe
|
||||
```
|
||||
|
||||
To remove an item from `localStorage` using its key, you can use the `removeItem()` method.
|
||||
|
||||
```js
|
||||
localStorage.removeItem('username');
|
||||
```
|
||||
|
||||
To clear all data in `localStorage`, you can use the `clear()` method.
|
||||
|
||||
```js
|
||||
localStorage.clear();
|
||||
```
|
||||
|
||||
Now, let’s take a look at an example where we use `localStorage` to store the preferred theme of a user.
|
||||
|
||||
```js
|
||||
// Store the user's theme preference
|
||||
localStorage.setItem('theme', 'dark');
|
||||
|
||||
// Retrieve the stored theme preference
|
||||
const userTheme = localStorage.getItem('theme');
|
||||
console.log(userTheme); // 'dark'
|
||||
|
||||
// Remove the theme preference
|
||||
localStorage.removeItem('theme');
|
||||
|
||||
// Clear all localStorage data
|
||||
localStorage.clear();
|
||||
```
|
||||
|
||||
In this example:
|
||||
|
||||
- We first store a theme choice (`dark`) for the user.
|
||||
|
||||
- We then retrieve that theme and output it to the console.
|
||||
|
||||
- Finally, we demonstrate how to remove a specific item or clear all stored data.
|
||||
|
||||
`localStorage` is very useful for storing small pieces of data that need to persist between sessions, but it's important to note that `localStorage` should not be used to store sensitive information, such as passwords, because it can pose security risks.
|
||||
|
||||
# --questions--
|
||||
|
||||
|
||||
@ -1,14 +1,86 @@
|
||||
---
|
||||
id: 6733ff5814129c48b4fca88e
|
||||
title: What Is sessionStorage, and What Are Some Common Methods?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
challengeType: 19
|
||||
# videoId: nVAaxZ34khk
|
||||
dashedName: what-is-sessionstorage-and-what-are-some-common-methods
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the lecture video and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
In the previous lecture video, we learned about working with `localStorage` and were briefly introduced to `sessionStorage`.
|
||||
|
||||
Recall, that `sessionStorage` is when the data is cleared as soon as the user closes the tab or window in which the web application is running. It’s ideal for situations where data only needs to persist for the length of a single session, such as maintaining form data during navigation or storing temporary state information during a checkout process.
|
||||
|
||||
Much like `localStorage`, `sessionStorage` uses key-value pairs to store and retrieve data. The methods used with `sessionStorage` are also the same as `localStorage`, with the only real difference being how long the data is stored.
|
||||
|
||||
Here are a few examples of working with the different methods:
|
||||
|
||||
- `sessionStorage.setItem()`: Stores a key-value pair in `sessionStorage`.
|
||||
|
||||
```js
|
||||
sessionStorage.setItem('cart', '3 items');
|
||||
```
|
||||
|
||||
- `sessionStorage.getItem()`: Retrieves the value of a given key from `sessionStorage`.
|
||||
|
||||
```js
|
||||
let cart = sessionStorage.getItem('cart');
|
||||
console.log(cart); // Outputs: '3 items'
|
||||
```
|
||||
|
||||
- `sessionStorage.removeItem()`: Removes a specific item from `sessionStorage` using its key.
|
||||
|
||||
```js
|
||||
sessionStorage.removeItem('cart');
|
||||
```
|
||||
|
||||
- `sessionStorage.clear()`: Clears all data stored in `sessionStorage`.
|
||||
|
||||
```js
|
||||
sessionStorage.clear();
|
||||
```
|
||||
|
||||
Let’s look at an example where we store data in `sessionStorage` which only lasts as long as the browser tab or window is open:
|
||||
|
||||
```js
|
||||
// Store data in sessionStorage
|
||||
sessionStorage.setItem('currentUser', 'JohnDoe');
|
||||
|
||||
// Retrieve the stored data
|
||||
const user = sessionStorage.getItem('currentUser');
|
||||
console.log(user); // 'JohnDoe'
|
||||
|
||||
// Remove a specific key from sessionStorage
|
||||
sessionStorage.removeItem('currentUser');
|
||||
|
||||
// Clear all sessionStorage data
|
||||
sessionStorage.clear();
|
||||
```
|
||||
|
||||
In this example, we:
|
||||
|
||||
1. Store the current user’s name (`JohnDoe`) in `sessionStorage`.
|
||||
|
||||
2. Retrieve and display it.
|
||||
|
||||
3. Remove the item associated with the key `currentUser`.
|
||||
|
||||
4. Clear all `sessionStorage` data.
|
||||
|
||||
The key difference from `localStorage` is that as soon as the user closes the tab, all stored session data will be lost.
|
||||
|
||||
`sessionStorage` is particularly useful in scenarios like:
|
||||
|
||||
- Storing temporary data such as form entries during a multi-page form process.
|
||||
|
||||
- Storing temporary selections or preferences that don’t need to persist across sessions.
|
||||
|
||||
- Maintaining state on a single-page application that doesn’t need to be remembered once the tab is closed.
|
||||
|
||||
`sessionStorage` ensures that once the user leaves the page, the session data is cleared, which is great for scenarios where you don’t want to hold onto information beyond the current session.
|
||||
|
||||
# --questions--
|
||||
|
||||
|
||||
@ -1,14 +1,70 @@
|
||||
---
|
||||
id: 6733ff6f02dde548ebe4a6d5
|
||||
title: What Are Cookies, and How Do They Work?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
challengeType: 19
|
||||
# videoId: nVAaxZ34khk
|
||||
dashedName: what-are-cookies-and-how-do-they-work
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the lecture video and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
Cookies, also known as web cookies or browser cookies, are small pieces of data that a server sends to a user's web browser. These cookies are stored on the user's device and sent back to the server with subsequent requests.
|
||||
|
||||
Cookies are essential in helping web applications maintain state and remember user information, which is especially important since HTTP is a stateless protocol.
|
||||
|
||||
Cookies can store a variety of information such as user preferences, session data, or tracking information.
|
||||
|
||||
Cookies are always stored as name-value pairs. This means each cookie has a name (key) and an associated value.
|
||||
|
||||
For example, a cookie might store a user's session ID like this: `sessionId=abc123`. The key is `sessionId`, and the value is `abc123`. Each time the browser communicates with the server, the browser sends these cookies in the form of name-value pairs.
|
||||
|
||||
When a user visits a website, the server can send one or more cookies to the user's browser by including a Set-Cookie header in the HTTP response. A header is a key-value pair that provides additional information about the HTTP request or response. You will learn more about HTTP requests and responses in future lectures.
|
||||
|
||||
Once the cookies are set, the browser stores them and automatically includes them in the Cookie header with every subsequent request to the same domain. This allows the server to access the stored cookies and use them for things like maintaining user sessions or tracking preferences.
|
||||
|
||||
Here’s an example of how a cookie is set in an HTTP response:
|
||||
|
||||
```http
|
||||
Set-Cookie: sessionId=abc123; Expires=Wed, 21 Oct 2021 07:28:00 GMT; Secure; HttpOnly
|
||||
```
|
||||
|
||||
The browser will store the cookie, and in future requests to the same server, it will include the cookie in the `Cookie` header:
|
||||
|
||||
```http
|
||||
Cookie: sessionId=abc123
|
||||
```
|
||||
|
||||
The server can then read the cookie and use the stored session ID to retrieve information about the user, such as whether they are logged in.
|
||||
|
||||
Here is a breakdown of the different types of cookies.
|
||||
|
||||
- Session Cookies only last for the duration of the user's session on the website. Once the user closes the browser or tab, the session cookie is deleted. These cookies are typically used for tasks like keeping a user logged in during their visit.
|
||||
|
||||
- Persistent Cookies have an expiration date and remain stored on the user's device until that date is reached. Persistent cookies are often used for remembering user preferences or login details across sessions.
|
||||
|
||||
- Secure Cookies are only sent over HTTPS, ensuring that they cannot be intercepted by an attacker in transit.
|
||||
|
||||
- HttpOnly Cookies cannot be accessed or modified by JavaScript running in the browser, making them more secure against cross-site scripting (XSS) attacks. cross-site scripting (XSS) attacks happen when an attacker injects malicious scripts into a web page that is viewed by other users. These scripts can then execute in the context of the victim's browser, potentially stealing cookies, session data, or performing other malicious actions without the user's knowledge or consent. By marking cookies as HttpOnly, they are protected from being accessed via JavaScript, reducing the risk of such attacks.
|
||||
|
||||
You can create cookies via server responses using the `Set-Cookie` header or through JavaScript using `document.cookie`.
|
||||
|
||||
Here's an example of setting a cookie using JavaScript:
|
||||
|
||||
```js
|
||||
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2021 23:59:59 GMT; path=/";
|
||||
```
|
||||
|
||||
This command sets a cookie named `username` with the value `"JohnDoe"` that will expire at the end of 2021. You can update an existing cookie by simply setting it again with a new value.
|
||||
|
||||
To delete a cookie, you set its expiration date in the past:
|
||||
|
||||
```js
|
||||
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
|
||||
```
|
||||
|
||||
This will remove the `username` cookie from the browser.
|
||||
|
||||
# --questions--
|
||||
|
||||
|
||||
@ -1,14 +1,34 @@
|
||||
---
|
||||
id: 6733ff8d06376149474a0c0d
|
||||
title: What Is the Cache API, and How Does It Work?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
challengeType: 19
|
||||
# videoId: nVAaxZ34khk
|
||||
dashedName: what-is-the-cache-api-and-how-does-that-work
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the lecture video and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
The Cache API is used to store network requests and responses, making web applications work more efficiently and even function offline. It is part of the broader Service Worker API and is crucial for creating Progressive Web Apps (PWAs) that can work under unreliable or slow network conditions.
|
||||
|
||||
Before we continue with the Cache API, we first need to understand how service workers, PWAs, and network requests work on a basic level.
|
||||
|
||||
A Network request is a request made by a web browser or application to a server to retrieve data or resources over the internet. For example, when you visit a website, your browser sends a network request to the web server to get the files (such as HTML, images, or videos) needed to display the page.
|
||||
|
||||
A service worker is a special type of JavaScript file that runs in the background of a web application, separate from the main browser thread. It acts as a middleman between the web page and the network, allowing developers to intercept network requests, cache resources, and handle things like push notifications or background sync.
|
||||
|
||||
A PWA, or Progressive Web App, is a type of web application that uses modern web technologies to provide a native app-like experience on the web. PWAs are designed to work reliably on any device, regardless of network conditions, and can be accessed through a browser or installed on a user's device like a traditional app.
|
||||
|
||||
Now that we have a better understanding of service workers, PWAs, and network requests, we can dive deeper into the Cache API.
|
||||
|
||||
The Cache API is a storage mechanism that stores `Request` and `Response` objects. When a request is made to a server, the application can store the response and later retrieve it from the cache instead of making a new network request. This reduces load times, saves bandwidth, and improves the overall user experience.
|
||||
|
||||
The browser provides a storage area known as Cache Storage, where developers can save key-value pairs of network requests and their corresponding responses.
|
||||
|
||||
With the Cache-Control header, developers can specify how long a cached resource should remain stored, as well as whether it should be revalidated or served directly from the cache.
|
||||
|
||||
By using the Cache API, developers can build offline-first web applications, allowing a PWA, for example, to serve cached assets when the user is disconnected from the network.
|
||||
|
||||
# --questions--
|
||||
|
||||
|
||||
@ -1,14 +1,55 @@
|
||||
---
|
||||
id: 6733ff9d2fb9c449af68ad99
|
||||
title: What Are Some Negative Patterns Associated with Client-Side Storage?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
challengeType: 19
|
||||
# videoId: nVAaxZ34khk
|
||||
dashedName: what-are-some-negative-patterns-associated-with-client-side-storage
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the lecture video and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
Client-side storage allows websites to store data on a user's device. However, like many technologies, it can be misused.
|
||||
|
||||
Let’s explore some negative patterns associated with client-side storage, focusing on cookies and their misuse for tracking and fingerprinting.
|
||||
|
||||
Let's start with cookies.
|
||||
|
||||
In an earlier lecture video, you learned that cookies are data stored on a user's device when they visit a web app. A common misuse of cookies is excessive tracking.
|
||||
|
||||
Websites use cookies to track a user's interactions with a web app, creating a history of their digital activities. This is done for targeted advertising but can raise significant privacy concerns.
|
||||
|
||||
For example, a shopping website might use a tracking cookie like this:
|
||||
|
||||
```js
|
||||
document.cookie = "userID=123; path=/; expires=Thu, 18 Dec 2024 6:00:00 UTC";
|
||||
```
|
||||
|
||||
This code sets a cookie named `userID` with a value of `123`. The cookie will be sent with every request to the website, allowing it to track the user's actions. While this might seem harmless, imagine hundreds of websites sharing this information – it could create a very detailed picture of your online life and choices.
|
||||
|
||||
Another concerning practice is browser fingerprinting.
|
||||
|
||||
This technique uses client-side information to create a unique "fingerprint" of a user's browser. Websites have the ability to gather information about your browser version, installed plugins, screen resolution, and other data to uniquely identify you.
|
||||
|
||||
Here's a simple example of how a website can create a fingerprint of you:
|
||||
|
||||
```js
|
||||
let fingerprintExample = navigator.userAgent + screen.width + screen.height;
|
||||
console.log(fingerprintExample);
|
||||
```
|
||||
|
||||
This code combines your browser's user agent with your screen dimensions. While this is a basic example, real fingerprinting methods are much more complex and can be highly accurate in identifying users.
|
||||
|
||||
Local Storage can also be misused as some websites use it to store sensitive information insecurely. For instance:
|
||||
|
||||
```js
|
||||
localStorage.setItem('userPassword', 'someonesPasswordHere');
|
||||
```
|
||||
|
||||
This code stores a user's password in Local Storage. This is a serious security risk as the data in Local Storage is not encrypted and can be accessed easily.
|
||||
|
||||
In conclusion, while client-side storage offers many benefits, it's crucial to use it responsibly. As you continue your web development journey, always consider the privacy and security of your users' data on the client side.
|
||||
|
||||
# --questions--
|
||||
|
||||
|
||||
@ -1,14 +1,46 @@
|
||||
---
|
||||
id: 6733ffacd0ad1e49ec2af051
|
||||
title: How Can You Use Cookies to Store Arbitrary Data, Normally Controlled by HTTP Headers?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
challengeType: 19
|
||||
# videoId: nVAaxZ34khk
|
||||
dashedName: how-can-you-use-cookies-to-store-arbitrary-data-normally-controlled-by-http-headers
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the lecture video and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
As you learned in previous lectures, cookies are simple data that websites can store on a user's device.
|
||||
|
||||
However, you can actually store more complex data structures in cookies. One common method is to use JSON to store objects or arrays. Here's an example:
|
||||
|
||||
```js
|
||||
const userData = {
|
||||
name: "John Doe",
|
||||
age: 30,
|
||||
role: "admin"
|
||||
};
|
||||
|
||||
document.cookie = "userInfo=" + JSON.stringify(userData) + "; path=/";
|
||||
```
|
||||
|
||||
In this example, we're creating an object with user data, converting it to a JSON string, and then storing it in a cookie. When we want to retrieve this data, we can parse the JSON string into an object using `JSON.parse()`.
|
||||
|
||||
Now, you might be wondering about the “HTTP headers” aspect of our topic. Typically, cookies are set by the server using HTTP headers.
|
||||
|
||||
For example, a server might send a header like this:
|
||||
|
||||
```http
|
||||
Set-Cookie: username=John Doe; expires=Thu, 31 Dec 2024 6:00:00 IST; path=/
|
||||
```
|
||||
|
||||
This header tells the browser to set a cookie.
|
||||
|
||||
We can also set cookies directly in the browser using JavaScript. This is useful for storing data that doesn't need to be sent to the server immediately.
|
||||
|
||||
Please note that cookies have a size limit of around 4KB, and storing too much data in them may slow down your web app.
|
||||
|
||||
Storing large amounts of data in cookies can increase network traffic as cookies are sent with every HTTP request.
|
||||
|
||||
# --questions--
|
||||
|
||||
|
||||
@ -1,14 +1,92 @@
|
||||
---
|
||||
id: 6733ffb59c62ee4a23522efe
|
||||
title: What Is IndexedDB, and How Does It Work?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
challengeType: 19
|
||||
# videoId: nVAaxZ34khk
|
||||
dashedName: what-is-indexeddb-and-how-does-it-work
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the lecture video and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
IndexedDB is a tool for storing structured data in the browser. This is built into modern web browsers, allowing web apps to store and fetch JavaScript objects efficiently.
|
||||
|
||||
Unlike other storage mechanisms like localStorage, which is limited to storing strings, IndexedDB can store JavaScript objects, files, and pretty much any other type of data. This makes it easy for web applications that need to work with large and complex data structures.
|
||||
|
||||
Now, let's look at how IndexedDB works.
|
||||
|
||||
The first step is to open a database. Here's an example:
|
||||
|
||||
```js
|
||||
let request = indexedDB.open("Sample DB", 1);
|
||||
|
||||
request.onerror = function(event) {
|
||||
console.log("Error opening database");
|
||||
};
|
||||
|
||||
request.onsuccess = function(event) {
|
||||
let db = event.target.result;
|
||||
console.log("Database opened successfully");
|
||||
};
|
||||
```
|
||||
|
||||
In this code, we're opening a database named `"Sample DB"` with version 1. We provide two callback functions: one for handling errors, and another for when the database is successfully opened. The 'db' object we get in the success callback is what we'll use to interact with the database.
|
||||
|
||||
If you check the browser dev tools application interface, you will see your `Sample DB` in the `IndexedDb` section has been opened. Once you have your database open, you can start working with object stores.
|
||||
|
||||
Object stores in IndexedDB are similar to tables in traditional databases. They hold the actual data you want to store. Here's how to create an object store:
|
||||
|
||||
```js
|
||||
request.onupgradeneeded = function(event) {
|
||||
let db = event.target.result;
|
||||
let objectStore = db.createObjectStore("customers", { keyPath: "id" });
|
||||
};
|
||||
```
|
||||
|
||||
This code creates an object store named `"customers"` with `"id"` as its key path. The key path is like a primary key in a traditional database - it's used to uniquely identify each record.
|
||||
|
||||
To add data to our object store, we'd do something like this. The `db` in this example represents the IndexedDB database instance.
|
||||
|
||||
```js
|
||||
let transaction = db.transaction(["customers"], "readwrite");
|
||||
let objectStore = transaction.objectStore("customers");
|
||||
let request = objectStore.add({ id: 1, name: "John Doe", email: "john@example.com" });
|
||||
|
||||
request.onerror = function(event) {
|
||||
console.log("Error adding data");
|
||||
};
|
||||
|
||||
request.onsuccess = function(event) {
|
||||
console.log("Data added successfully");
|
||||
};
|
||||
```
|
||||
|
||||
This code adds a new customer to our `"customers"` object store. We start a transaction (which is how we group database operations), get a reference to our object store, and then add our data.
|
||||
|
||||
Retrieving data works in a similar way. We start a transaction, get our object store, and then use methods like `get` to retrieve data:
|
||||
|
||||
```js
|
||||
let transaction = db.transaction(["customers"]);
|
||||
let objectStore = transaction.objectStore("customers");
|
||||
let request = objectStore.get(1);
|
||||
|
||||
request.onerror = function(event) {
|
||||
console.log("Error retrieving data");
|
||||
};
|
||||
|
||||
request.onsuccess = function(event) {
|
||||
console.log("Customer:", request.result);
|
||||
};
|
||||
```
|
||||
|
||||
This code retrieves the customer with `id` `1` from our `"customers"` object store.
|
||||
|
||||
One of the key features of IndexedDB is that it's asynchronous.
|
||||
|
||||
This means that when you interact with IndexedDB, operations don't block the main thread of the web application. This ensures that your web application remains responsive even when dealing with large amounts of data.
|
||||
|
||||
While IndexedDB provides powerful capabilities, it has a steeper learning curve compared to other simpler storage API options which can be challenging for beginners. However, for applications that need to handle large amounts of structured data on the client-side, IndexedDB offers unparalleled capabilities.
|
||||
|
||||
# --questions--
|
||||
|
||||
|
||||
@ -1,14 +1,30 @@
|
||||
---
|
||||
id: 6733ffc7353af34a61ed683a
|
||||
title: What Are Cache and Service Workers, and How Do They Work?
|
||||
challengeType: 11
|
||||
videoId: nVAaxZ34khk
|
||||
challengeType: 19
|
||||
# videoId: nVAaxZ34khk
|
||||
dashedName: what-are-cache-service-workers-and-how-do-they-work
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Watch the lecture video and answer the questions below.
|
||||
The video for this lecture isn't available yet, one will be available soon. Here is a transcript of the lecture for now:
|
||||
|
||||
Caching is the process of storing copies of files in a temporary storage location so they can be accessed more quickly.
|
||||
|
||||
When you visit a website, your browser can save certain files (such as images, CSS, and JavaScript) locally. This means that the next time you visit the same site, it can load these files from your device instead of fetching them again from a server, making the site load faster.
|
||||
|
||||
A Service Worker is a script that runs in the background, separate from your web page. It can intercept network requests, access the cache, and enable the web app to work offline. It is a key component of Progressive Web Apps.
|
||||
|
||||
So, how do Cache and Service Workers work together in Progressive Web Apps?
|
||||
|
||||
PWAs are web apps that can offer an app-like experience. They can work offline, send push notifications, and even be installed on the home screen of a mobile device or computer.
|
||||
|
||||
When a user first visits a PWA, the Service Worker can cache important files.
|
||||
|
||||
Users can continue to use the app offline, and when they come back online, any upcoming changes can be synced with the server.
|
||||
|
||||
The combination of caching and Service Workers enables web apps to provide a fast and reliable experience even in poor network conditions.
|
||||
|
||||
# --questions--
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user