teleren/devto huggingface dataset:
Sharing data between siblings components using Context in React with Hooks
Tags: react, context, hooks, javascript
Published: 2022-01-31 03:30:59

Context in react was designed to share data or props in your app making this info available globally for a tree of components. In few words allows you to pass this info between any component without having to explicitly pass a prop through every level of the tree, like from parents to child for example. Before using Context is important to know that it's generally used when some data needs to be accessible by many components at different nesting levels. So how we use it?

Let's say we need a prop called posts that needs to be available in few components of your app. The first thing will be to create a folder in your application called context which will contain your PostContext .jsx or .js file. Let's also say that we need to set the initial State of this prop as an empty array. So we can have something like this: 

```cassandraql
import React, { createContext, useState } from "react";


const PostContext = createContext(null);
const PostDispatchContext = createContext(null);

function PostProvider({ children }) {
    const [posts, setPosts] = useState([]);
  
    return (
      <PostContext.Provider value={posts}>
        <PostDispatchContext.Provider value={setPosts}>
          {children}
        </PostDispatchContext.Provider>
      </PostContext.Provider>
    );
  }
  
  export { PhotoProvider, PhotoContext, PhotoDispatchContext };
```
We import createContext & useState from the react library. This will allow us to create two const, first the Postcontext itself which allows to query the context state and the PostDispatchContext to mutate the context state. We can set that to null or undefined. 

Now we just need to create a function to define our provider and pass the children components that will use the data we are trying to share. It's important to mention that a "provider" is used to encapsulate only the components that needs the state in this context. we will see that later on. Finally we assign the state using the useState Hook and set an empty array as shown. Once this logic is defined we render the value of the context and wrap the values we need to expose later through the children components. It might sounds complicated but all we are doing here is to share the initial state of our prop and make it available through the provider. Once this is set It's time to export the provider PostProvider.


Let's wrap the components that will use the posts and setPosts as Props.  

```cassandraql

function App() {
  return (
    <>
      <PostProvider>
        <User />
        <Comments />
     </PostProvider>
    <>
  );
}

```
Now posts is available globally in your app and useful for the components wrap with the provider. Due the nature of react context It is really important to make this props available on the components that really need them only. This is to avoid any performance drain in your app. Check the second part where I explain how to finally set the data for each components using useContext hook. 

Happy Coding
Wikipedia API Contextualized and Leveraged
Published: 2022-01-31 03:30:03

First, an **application programming interface** (API) is a connection between computers or between computer programs that allow applications to talk to each other. They are very versatile and basically act like a mutual friend between both systems. 

We will be walking through how APIs are visualized, how they work, and how the JSON response is used. The example that we will be contextualizing is Wikipedia's API and how we can leverage it using the Wikipedia query tag.

## Fetch
The main goal for us here is to communicate with Wikipedia's API so that we can render their content on our own projects! We can do this by using the `fetch` tag. It is "behind the scenes" of the web component. It is what starts the process to retrieve information through APIs. In this case, the `fetch` tag is used to communicate with Wikipedia to find the respective article so that it can be rendered on the page. In the source code of the Wikipedia query, it shows the `fetch` tag requesting the address which then leads to the JSON API response.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cqe45udiulbvjcoui1p9.png)

## APIs Visualized
The Wikipedia query tag communicates with Wikipedia's API service by searching for a Wikipedia article with the title specified. In this image of the Wikipedia query source code, you can see that the code is grabbing the Wikipedia article based on the search that the user will input. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xw22bqe39ffvkgr95q6w.png)
To include the Wikipedia query in your own projects, the following syntax can be implemented. Below, we are specifying that the Wikipedia articles should be searched by the location specified by the user![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zyb3c4o8au7w7dwqjyku.png)
**JSON Response and Display**
The JSON response is the default result of the fetch request because it is easily readable and easy to translate. When the JSON response is received, the web components are displayed on your own projects!

You can find more information about APIs [here](https://www.redhat.com/en/topics/api/what-are-application-programming-interfaces). For more information about the Wiki API, you can find its documentation [here](https://en.wikipedia.org/w/api.php)! For reference I have attached my own GitHub [repository](https://github.com/abbeylyle4/ip-project/blob/master/src/LocationFromIP.js).
Web Servers Installtion- Apache, Ngnix, LiteSpeed and IIS
Tags: webdev, servers, tutorial, opensource
Published: 2022-01-31 03:10:53

Web Server:-

Web server is a computer where the web content is stored. Basically a web server is used to host the web sites but there exists other web servers also such as gaming, storage, FTP, email etc.

Web Server Working

Web server respond to the client request in either of the following two ways:

- Sending the file to the client associated with the requested URL.
- Generating response by invoking a script and communicating with database


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xfttjepstcwh0cqafoke.jpg)
	
Apache Installation On Ubuntu

Apache is an open source web server that’s available for Linux servers free of charge.

Prerequisites

- Ubuntu Server 20.04 LTS
- Secure Shell (SSH) access to your server
- Basic Linux command line knowledge

Step1:-  Installing Apache
Step2:- Creating Your Own Website
Step3:-Setting up the VirtualHost Configuration File
Step4:-Activating VirtualHost file

Nginx Installation On Ubuntu

NGINX is open source software for web serving, reverse proxying, caching, load balancing, media streaming, and more. It started out as a web server designed for maximum performance and stability.

Prerequisites

- Ubuntu Server 20.04 LTS
- Secure Shell (SSH) access to your server
- Basic Linux command line knowledge

Step1:- Installing Nginx
Step 2:-  Adjusting the Firewall
Step3:- Checking your Web Server
Step4:- Managing the Nginx Process
Step5:- Setting Up Server Blocks

LiteSpeed Installation On Ubuntu

OpenLiteSpeed is a high-performance, lightweight, open source HTTP server edition of LiteSpeed Web Server Enterprise.

Prerequisites

- Ubuntu Server 20.04 LTS
- Secure Shell (SSH) access to your server
- Basic Linux command line knowledge

Step 1: Add LiteSpeed Repository to Ubuntu 20.04
Step 2: Install OpenLiteSpeed onUbuntu 20.04
Step 3: Install PHP onUbuntu 20.04
Step 4: Setting the Administrative Password
Step 5: Access OpenLiteSpeed Web Admin onUbuntu 20.04
Step 6: Creating a Test Virtual Host on OpenLiteSpeed
Step 7: Change default Virtual Host Listening Port

IIS Server Installation on Windows

Internet Information Services is the feature of the Windows 10/8/7 or server running Desktop or Server hardware to provide a localhost web server. It is developed by Microsoft and only available in Windows.

Step 1: Run PowerShell as Admin
Step 2: Install IIS services
Command:- _Enable-WindowsOptionalFeature -Online -FeatureName <service-name>_
Step3:- Run IIS Server
Coding the Signout API for Breeze Lakes Point Next Project
Tags: javascript, nextjs, sideprojects, tutorial
Published: 2022-01-31 02:59:18


[Breeze Lakes Point](https://breeze-lakes-point-2.vercel.app/) is a demo I have been working on as a personal project. The goal for the site is to allow users to register information and admins to manage that information. The original setup for this project was a React front-end with a Rails API backend. After taking the Frontend Masters workshop [Build Full-Stack Apps from Scratch](https://frontendmasters.com/workshops/fullstack-apps/) taught by Scott Moss, I pivoted to start a new version using [Next.js](https://nextjs.org/) for the full solution.

I started the current project version from the Next.js `create-next-app` api and used the sample app from the workshop as reference. I was looking forward to leveraging the page routing and APIs that Next.js provides as part of its framework.

While the workshop covered how to log in an existing user and create a new user for the sample app, we did not cover signing out; the token we issued simply expired within 8 hours. For the purposes of my demo app, however, I wanted to demonstrate that a user could expect to log out explicitly at the end of a session by including an API for siging out.

I knew that the solution would involve adjusting the existing cookie to expire the token created by the app. I considered there must be a way to change the expiration date within the token. I did some Google searches for such a technique but did not find any leads.

Ultimately, the answer was very straightforward - write a blank `jwt` back to the cookie. This effectively removes the authorization for the user. The resulting API for `signout` was very basic, updating the `BREEZE_LAKES_POINT_ACCESS_TOKEN`:

```Javascript
import cookie from "cookie";
import { NextApiRequest, NextApiResponse } from "next";

export default async (req: NextApiRequest, res: NextApiResponse) => {
  res.setHeader(
    "Set-Cookie",
    cookie.serialize("BREEZE_LAKES_POINT_ACCESS_TOKEN", "", {
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax",
      path: "/",
    })
  );
  res.status(200).json({ msg: "Logout complete" });
};
```

In my navigation component, I ensured `next/router` was imported and added the `signout` route as a form with a single button so action could be taken on submit; once sign out is completed by the API, the user is sent back to the sign in page:

```JavaScript
import { useRouter } from "next/router";
...
const LeftNav = () => {
  const router = useRouter();

  const handleSubmit = async (e: any) => {
    e.preventDefault();

    const response = await signout("signout");
    router.push("/signin");
  };

  return (
...
```

I was able to verify this solution worked both locally and on my app deployed to [Vercel](https://vercel.com/). There is still more testing to be done but the initial implementation of the sign out feature was an excellent addition to the [Breeze Lakes Point](https://breeze-lakes-point-2.vercel.app/) demo project.
Best Way to Learn New Technology : 🧑🏻‍💻
Tags: programming, learning, tips
Published: 2022-01-31 02:54:30

This is not a big mistake. This is something which all programmers do all the time Including me, and that is trying to skip the documentation and trying to work with new technology by yourself.

This is fairly common If you are working with tools or softwares, Not exactly a programming language. For example, like cloud service (AWS), softwares, softwares as a web-services kind of things. We just jump into the UI and start using it.

However, like Quote says that, "You can save lots of hours of debugging If you just spend 10 min of time reading the documentation". If you not reading the documentation you could be reading unreliable sources. you could be reading from old sources. If the documentation available, why not just go ahead and do that ?

My best practice is to actually take official documentation If it is available or else you can stick to video tutorial or playlist. But also have an eye on what the official documentation says. 

                 **  "Happy Learning". **

** -Raj**
How IP Address, API and GeoIP Interact to Detect Logitude and Latitude
Published: 2022-01-31 02:38:41

I am still not completely sure on how all of the components are working together, but to the best of my abilities here is my explanation of what I think is happening.

## IP Address

The first API we see being used by this web component would be the IP Fast API that gives us the users exact location. The location is made up of the users IP address, city and country in this case and is portrayed below in the raw data image.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jemumgurn0p3u5v65ohn.png)

This API has been assigned to the object ipLookUp within the code. 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ratabgguc80308my35vd.png)

When parsing through and displaying the the information we get from the IP Fast API we have the next section of code. We see the operation `fetch` in relation to ipLookUp which we have established is our API object. Therefore, we are using the operation `fetch` to pull up our IP address from the API. the next section of code relates to whether or not the json data can be accessed, once that accessibility is given we are able to label and display our IP address.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ho2epn1x0xvttjiug4w9.png)

## warning! this is where I get a little confused!

Now that we have established our first API we "tag" it which is I think what is happening at the bottom of our `UserIP.js` file with this command: `customElements.define(UserIP.tag, UserIP);` I assume, but once again could be extremely wrong.

In order to interact with our second API we must move to a new file `LocationFromIP` where we see the data from `UserIP` being imported at the very beginning of the file.

## FREEGEOIP 

We see our second API GeoIP being introduced very similarly to the first, but this one has been named `locationEndpoint`. This API is where we gather our longitude and latitude and can finally put both together in the code below.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dyojud2ndpexl7q4nno8.png)

In this code we see the `locationEndpoint` which is our lat and long and our `userIPData.ip` and using the `fetch` function we are able to pool all of our info into one place to create a neat little location!

now, if you would like to take a look at mine I hate to break it to you but I am having some technical difficulties with pushing my code back up to github :( but for the sake of it I'm going to link it just incase I get it working soon--[link!](https://github.com/GigiFitiany/ip-project)
El arte del packaging y la importancia de un buen acabado en cartón según Gráficas Feli

Published: 2022-01-31 02:19:21

El packaging es un arte
Aunque el principal objetivo de cualquier empresa sea vender sus productos, sus esfuerzos deben estar dirigidos a todos los elementos necesarios para conseguirlo. Es decir, el verdadero reto se encuentra en hacer de sus productos algo atractivo para los clientes, que llame su atención y que motive la decisión de compra. En este sentido, el packaging es, de hecho, el arte de dar personalidad a un producto y hacerlo visualmente interesante para los clientes potenciales. En el mercado, un buen producto puede pasar completamente desapercibido si su envoltura es pobre o poco atractiva, por lo que es indispensable crear un empaque adecuado. Por esta razón, saber cuáles son las características de un buen packaging puede marcar la diferencia. Actualmente uno de los materiales en tendencia es el cartón, no solo porque es más económico y ofrece un sinfín de posibilidades, sino porque además, se trata de un material biodegradable y sostenible, algo muy valorado por las empresas de hoy. Es un elemento ideal para crear un packaging versátil y funcional.

La importancia del buen acabado sobre cartón
El cartón es, por lo tanto, una muy buena opción para elaborar una envoltura adecuada y efectiva, pero esto no es suficiente si el acabo final de la impresión no está a la altura. La impresión es tan importante como el empaque en sí, ya que en ella se encuentra la información de la marca junto con cualquier otro elemento importante que el vendedor desee plasmar sobre él. Por lo tanto, es sumamente importante que la impresión sea de buena calidad y tenga un acabado impecable, ya que eso no solo aporta una mejor imagen al producto, sino que además genera una mejor valoración en los clientes.

En Gráficas Feli cuentan con la experiencia, los conocimientos y las herramientas necesarias para lograr un acabado en cartón de calidad excepcional. De esta forma cualquier empresa, negocio o marca podrá tener asegurado un packaging personalizado de calidad, con una impresión que sobresalga y ponga al producto un paso por delante de la competencia.

[ver mas...](https://estartit.tv/)
La pala de pádel Orven Vulcano V2 de Orven Sport

Published: 2022-01-31 02:18:50

Características de la pala de pádel Orven Vulcano V2
La firma Orven Sport tiene presencia en países como Estados Unidos, Italia, Suecia, Japón, Malasia, Argentina, Francia y Alemania. La pala de pádel Orven Vulcano V2 es la mejor de la marca y está desarrollada para jugadores que buscan la máxima potencia sin perder el control ni la comodidad. Orven la define como su “buque insignia”.

El marco de la Vulcano V2 está fabricado con kevlar y fibra de vidrio, mientras que los puentes están reforzados con carbono. Ambas caras de la pala disponen de una doble capa de Carbono 6K Plain y fibra de vidrio de gran elasticidad. Asimismo, el equilibrio de la pala está desplazado hacia la punta, lo cual facilita golpes de gran potencia y solo pesa entre 350 y 370 gramos.

En la estética de la pala, se plasma la agresividad que permite al usarla en el juego. El color negro de su diseño representa el poder y el oro la excelencia, ya que además de ser efectiva y eficiente, su elegancia no pasa desapercibida.

Por otro lado, cuenta con una superficie menor que las palas redondas, las cuales son las más buscadas por los principiantes y su punto de gravedad es más elevado. En vez de estar en el mango, se encuentra en el centro de la pala. Esta característica es la que da la capacidad de que los golpes tengas más potencia y sean más precisos.

[ver mas...](https://estartit.tv/)
Front End Javascript: Working with APIs and IP Addresses
Tags: javascript, webdev, frontend, api
Published: 2022-01-31 02:08:50

## GeoIP API
To start, I wanted to briefly introduce the [API](https://freegeoip.app/json/) we will be working with to determine the latitude and longitude in the IP Address. Feel free to click on the link to explore what the else API can be used for.  


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4yrdfinc56ocmtz09nga.png) 

As you can see, we set the URL of the API as our location endpoint in our constructor of our LocationFromIP.js class, then: 

## IPFast API

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n50chbhwg52rdjlf2mxu.png)

Note, in the UpdateUserIP method of the UserIP.js class, the functionality of fetch; it grabs (or, fetches) the other [API](https://ip-fast.com/api/ip/?format=json&location=True) we are using to lookup the IP (`this.ipLookUp`) and returns the information (the IP address) if it can.

## Working with both APIs

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sc5z6xoosopqsf7ab1u1.png)

We work inside of the getGEOIPData method to fetch which data points we want to retrieve from the GeoIP API, such as long (longitude), lat (latitude), city, and region. To make it easier later, I also declared them as variables. Note the usage of the IPFast API here as well, as seen in the lines: 
`const IPClass = new UserIP();
 const userIPData = await IPClass.updateUserIP();`. 

Ideally, after the location is pulled from the GeoIP API, and the IP is pulled from the IPFast API, it should be able to be output later in the `render()` method when you want to show a map. 

## ...Did it work?
If you're lucky, yes! But did mine? Not quite. 
I will admit, I found this exercise to be very tricky and am not entirely sure I understand everything completely. If you want to try to check it out for yourself, feel free to check out this project on my [GitHub](https://github.com/hek5118/ip-project)!
Ixurkonea, la casa rural contemporánea ideal para disfrutar de unas vacaciones

Published: 2022-01-31 01:34:08

Una de las propiedades más destacadas del lugar es Ixurkonea, una casa abierta al público con capacidad para recibir hasta 10 personas. En ella, se combinan la tranquilidad de una casa rural y el confort de una construcción recién rehabilitada. Mikele Reparaz, dueña del inmueble y emprendedora hostelera, la equipó de manera contemporánea, sin perder ni una fracción del atractivo de la arquitectura tradicional.

Ixurkonea está rodeada de un paisaje extraordinario
La casa rural Ixurkonea está ubicada en el centro de Arbizu, villa destacada dentro de la comarca por sus fachadas cuidadas y sus balcones adornados. El caserío está a casi 500 metros de altura y su superficie, de término irregular, es de unos 14 kilómetros cuadrados. En la actualidad, la población suma 1.100 habitantes.

El pueblo cuenta con bares, restaurantes y comercios locales, además de un polideportivo con piscina cubierta, parques infantiles y una iglesia.

A su vez, el municipio está circundado por las sierras de Urbasa, Andía y Aralar. Desde las ventanas de la casa rural, es posible divisar la silueta del monte Benain, donde se encuentra la ermita de San Donato. Los visitantes más montañeros pueden ascender allí desde las proximidades de Ixurkonea. También hay una gran variedad de paseos de menor dificultad, con una completa red de senderos señalizados.

Sin dudas, el monte Benain es el dominador del paisaje en el valle y la marca de identidad de Arbizu. En la vegetación del lugar, predominan los robles, las hayas y los castaños. Los árboles, las sierras y los montes componen un paisaje único y espléndido.

[ver mas...](https://estartit.tv/)