folder names

This commit is contained in:
Jen Looper
2020-11-09 22:51:04 -05:00
parent 33e5d5f777
commit 1d81829ac1
367 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
*Complete this quiz by checking one answer per question.*
1. LocalStorage is cleared every time you close the browser window
- [ ] true
- [ ] false
2. The main browser window controls a browser's extension's LocalStorage
- [ ] true
- [ ] false
3. REST in an API context stands for
- [ ] Representational State Transfer
- [ ] Returning State Tasks
- [ ] Rendering State To Browser

View File

@@ -0,0 +1,20 @@
*A warm-up quiz about the browser*
Complete this quiz in class
1. APIs stand for
- [ ] Application Programming Interfaces
- [ ] A Programming Inference
- [ ] Anti Proven Intentions
2. Use an API to interact with
- [ ] Another web-connected asset
- [ ] A database
- [ ] Either of the above
3. Anyone can create an API
- [ ] true
- [ ] false

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 WebDev-For-Beginners
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,218 @@
# Browser Extension Project Part 2: Call an API, use Local Storage
## [Pre-lecture quiz](.github/pre-lecture-quiz.md)
### Introduction:
In this lesson, you'll call an API by submitting your browser extension's form and display the results in your browser extension. In addition, you'll learn about how you can store data in your browser's local storage for future reference and use.
✅ Follow the numbered segments in the appropriate files to know where to place your code
### 1. Set up the elements to manipulate in the extension:
By this time you have built the HTML for the form and results `<div>` for your browser extension. From now on, you'll need to work in the `/src/index.js` file and building your extension bit by bit. Refer to the [previous lesson](../about-browsers/README.md) on getting your project set up and on the build process.
Working in your `index.js` file, start by creating some `const` variables to hold the values associated with various fields:
```JavaScript
// form fields
const form = document.querySelector('.form-data');
const region = document.querySelector('.region-name');
const apiKey = document.querySelector('.api-key');
// results
const errors = document.querySelector('.errors');
const loading = document.querySelector('.loading');
const results = document.querySelector('.result-container');
const usage = document.querySelector('.carbon-usage');
const fossilfuel = document.querySelector('.fossil-fuel');
const myregion = document.querySelector('.my-region');
const clearBtn = document.querySelector('.clear-btn');
```
All of these fields are referenced by their css class, as you set it up in the HTML in the previous lesson.
### 2. Add listeners
Next, add event listeners to the form and the clear button that resets the form, so that if a user submits the form or clicks that reset button, something will happen, and add the call to initialize the app at the bottom of the file:
```JavaScript
form.addEventListener('submit', (e) => handleSubmit(e));
clearBtn.addEventListener('click', (e) => reset(e));
init();
```
✅ Notice the shorthand used to listen for a submit or click event, and how the event it is passed to the handleSubmit or reset functions. Can you write the equivalent of this shorthand in a longer format? Which do you prefer?
### 3. Build out the init() function and the reset() function:
Now you are going to build the function that initializes the extension, which is called init():
```JavaScript
function init() {
//if anything is in localStorage, pick it up
const storedApiKey = localStorage.getItem('apiKey');
const storedRegion = localStorage.getItem('regionName');
//set icon to be generic green
//todo
if (storedApiKey === null || storedRegion === null) {
//if we don't have the keys, show the form
form.style.display = 'block';
results.style.display = 'none';
loading.style.display = 'none';
clearBtn.style.display = 'none';
errors.textContent = '';
} else {
//if we have saved keys/regions in localStorage, show results when they load
displayCarbonUsage(storedApiKey, storedRegion);
results.style.display = 'none';
form.style.display = 'none';
clearBtn.style.display = 'block';
}
};
function reset(e) {
e.preventDefault();
//clear local storage for region only
localStorage.removeItem('regionName');
init();
}
```
In this function, there is some interesting logic. Reading through it, can you see what happens?
- two `const` are set up to check if the user has stored an APIKey and region code in local storage.
- if either of those is null, show the form by changing its style to display as 'block'
- hide the results, loading, and clearBtn and set any error text to an empty string
- if there exists a key and region, start a routine to:
- call the API to get carbon usage data
- hide the results area
- hide the form
- show the reset button
Before moving on, it's useful to learn about a very important concept available in browsers: [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). LocalStorage is a useful way to store strings in the browser as a `key-value` pair. This type of web storage can be manipulated by JavaScript to manage data in the browser. LocalStorage does not expire, while SessionStorage, another kind of web storage, is cleared when the browser is closed. The various types of storage have pros and cons to their usage.
> Note - your browser extension has its own local storage; the main browser window is a different instance and behaves separately.
You set your APIKey to have a string value, for example, and you can see that it is set on Edge by "inspecting" a web page (you can right-click a browser to inspect) and going to the Applications tab to see the storage.
![Local storage pane](images/localstorage.png)
✅ Think about situations where you would NOT want to store some data in LocalStorage. In general, placing API Keys in LocalStorage is a bad idea! Can you see why? In our case, since our app is purely for learning and will not be deployed to an app store, we will use this method.
Notice that you use the Web API to manipulate LocalStorage, either by using `getItem()`, `setItem()` or `removeItem()`. It's widely supported across browsers.
Before building the `displayCarbonUsage()` function that is called in `init()`, let's build the functionality to handle the initial form submission.
### 4. Handle the form submission
Create a function called `handleSubmit` that accepts an event argument `(e)`. Stop the event from propagating (in this case, we want to stop the browser from refreshing) and call a new function, `setUpUser`, passing in the arguments `apiKey.value` and `region.value`. In this way, you use the two values that are brought in via the initial form when the appropriate fields are populated.
```JavaScript
function handleSubmit(e) {
e.preventDefault();
setUpUser(apiKey.value, region.value);
}
```
✅ Refresh your memory - the HTML you set up in the last lesson has two input fields whose `values` are captured via the `const` you set up at the top of the file, and they are both `required` so the browser stops users from inputting null values.
### 5. Set up the user
Moving on to the `setUpUser` function, here is where you set local storage values for apiKey and regionName. Add a new function:
```JavaScript
function setUpUser(apiKey, regionName) {
localStorage.setItem('apiKey', apiKey);
localStorage.setItem('regionName', regionName);
loading.style.display = 'block';
errors.textContent = '';
clearBtn.style.display = 'block';
//make initial call
displayCarbonUsage(apiKey, regionName);
}
```
This function sets a loading message to show while the API is called. At this point, you have arrived at creating the most important function of this browser extension!
### 6. Display Carbon Usage
Finally it's time to query the API!
Before going further, we should discuss APIs. APIs, or [Application Programming Interfaces](https://www.webopedia.com/TERM/A/API.html), are a critical element of a web developer's toolbox. They provide standard ways for programs to interact and interface with each other. For example, if you are building a web site that needs to query a database, someone might have created an API for you to use. While there are many types of APIs, one of the most popular is a [REST API](https://www.smashingmagazine.com/2018/01/understanding-using-rest-api/).
✅ The term 'REST' stands for 'Representational State Transfer' and features using variously-configured URLs to fetch data. Do a little research on the various types of APIs available to developers. What format appeals to you?
There are important things to note about this function. First notice the [`async` keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). Writing your functions so that they run asynchronously means that they wait for an action, such as data being returned, to be completed before continuing.
Here's a quick video about `async`:
[![Async and Await for managing promises](https://img.youtube.com/vi/YwmlRkrxvkk/0.jpg)](https://youtube.com/watch?v=YwmlRkrxvkk "Async and Await for managing promises")
Create a new function to query the C02Signal API:
```JavaScript
import axios from '../node_modules/axios';
async function displayCarbonUsage(apiKey, region) {
try {
await axios
.get('https://api.co2signal.com/v1/latest', {
params: {
countryCode: region,
},
headers: {
'auth-token': apiKey,
},
})
.then((response) => {
let CO2 = Math.floor(response.data.data.carbonIntensity);
//calculateColor(CO2);
loading.style.display = 'none';
form.style.display = 'none';
myregion.textContent = region;
usage.textContent =
Math.round(response.data.data.carbonIntensity) + ' grams (grams C02 emitted per kilowatt hour)';
fossilfuel.textContent =
response.data.data.fossilFuelPercentage.toFixed(2) +
'% (percentage of fossil fuels used to generate electricity)';
results.style.display = 'block';
});
} catch (error) {
console.log(error);
loading.style.display = 'none';
results.style.display = 'none';
errors.textContent = 'Sorry, we have no data for the region you have requested.';
}
}
```
This is a big function. What's going on here?
- following best practices, you use an `async` keyword to make this function behave asyncronously. The function contains a `try/catch` block as it will return a promise when the API returns data. Because you don't have control over the speed that the API will respond (it may not respond at all!), you need to handle this uncertainty by call it asyncronously.
- you're querying the co2signal API to get your region's data, using your API Key. To use that key, you have to use a type of authentication in your header parameters.
- once the API responds, you assign various elements of its response data to the parts of your screen you set up to show this data.
- if there's an error, or if there is no result, you show an error message.
✅ Using asyncronous programming patterns is another very useful tool in your toolbox. Read [about the various ways](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) you can configure this type of code.
Congratulations! If you build your extension (`npm run build`) and refresh it in your extensions pane, you have a working extension! The only thing that isn't working is the icon, and you'll fix that in the next lesson.
---
## 🚀 Challenge
We've discussed several types of API so far in these lessons. Choose a web API and research in depth what it offers. For example, take a look at APIs available within browsers such as the [HTML Drag and Drop API](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API). What makes a great API in your opinion?
## [Post-lecture quiz](.github/post-lecture-quiz.md)
## Review & Self Study
You learned about LocalStorage and APIs in this lesson, both very useful for the professional web developer. Can you think how these two things work together? Think about how you would architect a web site that would store items to be used by an API.
## Assignment
[Adopt an API](assignment.md)

View File

@@ -0,0 +1,11 @@
# Adopt an API
## Instructions
APIs can be very fun to play with. Here is a [list of many free ones](https://github.com/public-apis/public-apis). Pick and API, and build a browser extension that solves a problem. It can be as small a problem of not having enough pet pictures (so, try the [dog CEO API](https://dog.ceo/dog-api/)) or something bigger - have fun!
## Rubric
| Criteria | Exemplary | Adequate | Needs Improvement |
| -------- | -------------------------------------------------------------------------- | ---------------------------------------- | ----------------------- |
| | A complete browser extension is submitted using an API from the above list | A partial browser extension is submitted | The submission has bugs |

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

View File

@@ -0,0 +1,212 @@
# Proyecto de extensión del navegador, parte 2: llamar a una API, usar almacenamiento local
## [Pre-lecture prueba](.github/pre-lecture-quiz.md)
### Introducción:
En esta lección, llamará a una API enviando el formulario de la extensión de su navegador y mostrará los resultados en la extensión de su navegador. Además, aprenderá cómo puede almacenar datos en el almacenamiento local de su navegador para referencia y uso futuros.
✅ Siga los segmentos numerados en los archivos correspondientes para saber dónde colocar su código
### 1. Configure los elementos para manipular en la extensión:
En este momento, ha creado el HTML para el formulario y los resultados `<div>` para la extensión de su navegador. De ahora en adelante, necesitará trabajar en el archivo `/src/index.js` y construir su extensión poco a poco. Consulte la [lección anterior](../about-browsers/ README.md) sobre cómo configurar su proyecto y el proceso de compilación.
Trabajando en su archivo `index.js`, comience creando algunas variables `const` para contener los valores asociados con varios campos:
```JavaScript
// form fields
const form = document.querySelector('.form-data');
const region = document.querySelector('.region-name');
const apiKey = document.querySelector('.api-key');
// results
const errors = document.querySelector('.errors');
const loading = document.querySelector('.loading');
const results = document.querySelector('.result-container');
const usage = document.querySelector('.carbon-usage');
const fossilfuel = document.querySelector('.fossil-fuel');
const myregion = document.querySelector('.my-region');
const clearBtn = document.querySelector('.clear-btn');
```
Todos estos campos están referenciados por su clase css, como lo configuró en el HTML en la lección anterior.
### 2. Agregar oyentes
A continuación, agregue detectores de eventos al formulario y el botón de borrar que restablece el formulario, de modo que si un usuario envía el formulario o hace clic en ese botón de restablecimiento, algo sucederá y agregue la llamada para inicializar la aplicación en la parte inferior del archivo:
```JavaScript
form.addEventListener('submit', (e) => handleSubmit(e));
clearBtn.addEventListener('click', (e) => reset(e));
init();
```
✅ Observe la abreviatura que se usa para escuchar un evento de envío o clic, y cómo el evento se pasa a las funciones handleSubmit o reset. ¿Puedes escribir el equivalente de esta abreviatura en un formato más largo? ¿Cual prefieres?
### 3. Desarrolle la init() y reset() función:
Ahora vas a construir la función que inicializa la extensión, que se llama `init()`:
```JavaScript
function init() {
//si hay algo en localStorage, recójalo
const storedApiKey = localStorage.getItem('apiKey');
const storedRegion = localStorage.getItem('regionName');
//establecer el icono en verde genérico
//todo
if (storedApiKey === null || storedRegion === null) {
//si no tenemos las claves, mostrar el formulario
form.style.display = 'block';
results.style.display = 'none';
loading.style.display = 'none';
clearBtn.style.display = 'none';
errors.textContent = '';
} else {
//si hemos guardado claves / regiones en localStorage, mostrar los resultados cuando se cargan
displayCarbonUsage(storedApiKey, storedRegion);
results.style.display = 'none';
form.style.display = 'none';
clearBtn.style.display = 'block';
}
};
function reset(e) {
e.preventDefault();
//borrar almacenamiento local solo para la región
localStorage.removeItem('regionName');
init();
}
```
En esta función, hay una lógica interesante. Al leerlo, ¿puedes ver lo que sucede?
- Se configuran dos `const` para verificar si el usuario ha almacenado una clave API y un código de región en el almacenamiento local.
- si alguno de ellos es nulo, muestre el formulario cambiando su estilo para que se muestre como 'bloque'
- ocultar los resultados, cargar y borrarBtn y establecer cualquier texto de error en una cadena vacía
- si existe una clave y una región, inicie una rutina para:
- llamar a la API para obtener datos de uso de carbono
- ocultar el área de resultados
- ocultar el formulario
- mostrar el botón de reinicio
Antes de continuar, es útil conocer un concepto muy importante disponible en los navegadores: [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). LocalStorage es una forma útil de almacenar cadenas en el navegador como un par "clave-valor". Este tipo de almacenamiento web puede ser manipulado por JavaScript para administrar datos en el navegador. LocalStorage no caduca, mientras que SessionStorage, otro tipo de almacenamiento web, se borra cuando se cierra el navegador. Los distintos tipos de almacenamiento tienen ventajas y desventajas para su uso.
> Nota: la extensión de su navegador tiene su propio almacenamiento local; la ventana principal del navegador es una instancia diferente y se comporta por separado.
Configura su APIKey para que tenga un valor de cadena, por ejemplo, y puede ver que está configurado en Edge "inspeccionando" una página web (puede hacer clic con el botón derecho en un navegador para inspeccionar) y yendo a la pestaña Aplicaciones para ver el almacenamiento.
![Panel de almacenamiento local](images/localstorage.png)
✅ Piense en situaciones en las que NO le gustaría almacenar algunos datos en LocalStorage. En general, colocar claves API en LocalStorage es una mala idea. ¿Puedes ver por qué? En nuestro caso, dado que nuestra aplicación es puramente para aprender y no se implementará en una tienda de aplicaciones, usaremos este método.
Tenga en cuenta que utiliza la API web para manipular LocalStorage, ya sea utilizando `getItem()`, `setItem()` o `removeItem()`. Es ampliamente compatible con todos los navegadores.
Antes de construir la función `displayCarbonUsage()` que se llama en `init()`, construyamos la funcionalidad para manejar el envío inicial del formulario.
### 4. Manejar el envío del formulario
Cree una función llamada `handleSubmit` que acepte un argumento de evento `(e)`. Detenga la propagación del evento (en este caso, queremos que el navegador no se actualice) y llame a una nueva función, `setUpUser`, pasando los argumentos `apiKey.value` y `region.value`. De esta manera, utiliza los dos valores que se introducen a través del formulario inicial cuando se completan los campos correspondientes.
```JavaScript
function handleSubmit(e) {
e.preventDefault();
setUpUser(apiKey.value, region.value);
}
```
✅ Refresque su memoria: el HTML que configuró en la última lección tiene dos campos de entrada cuyos `values` se capturan mediante la `const` que configuró en la parte superior del archivo, y ambos son `required` para que el navegador detenga a los usuarios de ingresar valores nulos.
### 5. Configurar el usuario
Pasando a la función `setUpUser`, aquí es donde configura los valores de almacenamiento local para apiKey y regionName. Agrega una nueva función:
```JavaScript
function setUpUser(apiKey, regionName) {
localStorage.setItem('apiKey', apiKey);
localStorage.setItem('regionName', regionName);
loading.style.display = 'block';
errors.textContent = '';
clearBtn.style.display = 'block';
//make initial call
displayCarbonUsage(apiKey, regionName);
}
```
Esta función establece un mensaje de carga para mostrar mientras se llama a la API. ¡En este punto, ha llegado a crear la función más importante de esta extensión de navegador!
### 6. Visualización del uso de carbono
¡Finalmente es hora de consultar la API!
Antes de continuar, deberíamos discutir las API. Las API, o [Interfaces de programación de aplicaciones](https://www.webopedia.com/TERM/A/API.html), son un elemento fundamental de la caja de herramientas de un desarrollador web. Proporcionan formas estándar para que los programas interactúen e interactúen entre sí. Por ejemplo, si está creando un sitio web que necesita consultar una base de datos, alguien podría haber creado una API para que la use. Si bien hay muchos tipos de API, una de las más populares es una [API REST](https://www.smashingmagazine.com/2018/01/understanding-using-rest-api/).
✅ El término 'REST' significa 'Transferencia de estado representacional' y características que utilizan URL configuradas de diversas formas para obtener datos. Investigue un poco sobre los distintos tipos de API disponibles para los desarrolladores. ¿Qué formato te atrae?
Hay cosas importantes a tener en cuenta sobre esta función. Primero observe la palabra clave `async`. Escribir sus funciones para que se ejecuten de forma asincrónica significa que
Cree una nueva función para consultar la API C02Signal:
```JavaScript
import axios from '../node_modules/axios';
async function displayCarbonUsage(apiKey, region) {
try {
await axios
.get('https://api.co2signal.com/v1/latest', {
params: {
countryCode: region,
},
headers: {
'auth-token': apiKey,
},
})
.then((response) => {
let CO2 = Math.floor(response.data.data.carbonIntensity);
//calculateColor(CO2);
loading.style.display = 'none';
form.style.display = 'none';
myregion.textContent = region;
usage.textContent =
Math.round(response.data.data.carbonIntensity) + ' grams (grams C02 emitted per kilowatt hour)';
fossilfuel.textContent =
response.data.data.fossilFuelPercentage.toFixed(2) +
'% (percentage of fossil fuels used to generate electricity)';
results.style.display = 'block';
});
} catch (error) {
console.log(error);
loading.style.display = 'none';
results.style.display = 'none';
errors.textContent = 'Sorry, we have no data for the region you have requested.';
}
}
```
Esta es una gran función. ¿Que está pasando aqui?
- siguiendo las mejores prácticas, utiliza una palabra clave `async` para hacer que esta función se comporte de forma asíncrona. La función contiene un bloque `try / catch` ya que devolverá una promesa cuando la API devuelva datos. Debido a que no tiene control sobre la velocidad a la que responderá la API (¡es posible que no responda en absoluto!), Debe manejar esta incertidumbre llamándola de forma asincrónica.
- está consultando la API co2signal para obtener los datos de su región, utilizando su clave API. Para usar esa clave, debe usar un tipo de autenticación en los parámetros de su encabezado.
- una vez que la API responde, asigna varios elementos de sus datos de respuesta a las partes de su pantalla que configura para mostrar estos datos.
- si hay un error o si no hay ningún resultado, muestra un mensaje de error.
✅ El uso de patrones de programación asíncronos es otra herramienta muy útil en su caja de herramientas. Lea [acerca de las diversas formas](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) puede configurar este tipo de código.
¡Felicidades! Si construye su extensión (`npm run build`) y la actualiza en su panel de extensiones, ¡tiene una extensión que funciona! Lo único que no funciona es el ícono, y lo solucionará en la próxima lección.
---
🚀 Desafío: hemos discutido varios tipos de API hasta ahora en estas lecciones. Elija una API web e investigue en profundidad lo que ofrece. Por ejemplo, eche un vistazo a las API disponibles en los navegadores, como la [API HTML de arrastrar y soltar] (https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API). En tu opinión, ¿qué hace que una API sea excelente?
## [Post-lecture prueba](.github/post-lecture-quiz.md)
## Revisión y autoestudio
Aprendió sobre LocalStorage y las API en esta lección, ambos muy útiles para el desarrollador web profesional. ¿Puedes pensar en cómo funcionan estas dos cosas juntas? Piense en cómo diseñaría un sitio web que almacenaría elementos para ser utilizados por una API.
**Tarea**: [Adopte una API](assignment.md)

View File

@@ -0,0 +1,11 @@
# Adopte una API
## Instrucciones
Puede ser muy divertido jugar con las API. Aquí hay una [lista de muchos gratuitos](https://github.com/public-apis/public-apis). Elija una API y cree una extensión de navegador que resuelva un problema. Puede ser un problema tan pequeño el no tener suficientes imágenes de mascotas (por lo tanto, pruebe la [API de CEO para perros](https://dog.ceo/dog-api/)) o algo más grande: ¡diviértase!
## Rúbrica
| Criterios | Ejemplar | Adecuado | Necesita mejorar |
| -------- | -------------------------------------------------- ------------------------ | ---------------------------------------- | ----------------------- |
| | Se envía una extensión de navegador completa utilizando una API de la lista anterior | Se envía una extensión de navegador parcial | La presentación tiene errores |