domingo, 14 de mayo de 2023

Daily tasks.- Using useEffect with a Simple Button in React Native

 Let's say we want to change the title of our application every time the user clicks on a button. First, we import useEffect and useState from the React library:



import React, { useState, useEffect } from 'react';
import { View, Text, Button } from 'react-native';

Then, we create our component and use useState to handle the state of the application's title:



const App = () => {
 
  const [title, setTitle] = useState('Mi aplicación');

useEffect(()=>{
  console.log('El componente se ha montado en la pantalla');
},[])
 

  return (
    <View>
      <Text>{title}</Text>
      <Button
        title="Cambiar título"
        onPress={() => setTitle('Nuevo título')}
      />
    </View>
  );
};

export default App;

In this example, we've used useState to handle the state of the application's title. setTitle is a function that allows us to update the state of the title when the user clicks on the button.

We've also used useEffect to log a message to the console every time the component mounts to the screen. We've added an empty second argument ([]) to indicate that this function should only be executed once, when the component mounts to the screen for the first time.

Finally, we've added a button that allows the user to change the application's title. When the user clicks on the button, the setTitle function is called to update the state of the title and change the text that is displayed on the screen.

With this, every time the user clicks on the button, the title of the application will be updated. I hope this example has helped you understand how to use useEffect with a simple button in React Native.

Daily tasks.-The loop of procrastination

 The loop of procrastination is a destructive cycle that many of us can fall into. It's a pattern of behavior where we put off tasks and responsibilities, feel guilty or anxious about not getting things done, and then continue to procrastinate instead of taking action.

The loop of procrastination can be frustrating and difficult to break out of, but it's not impossible. By understanding the loop and taking intentional steps to break it, we can develop healthier habits and improve our productivity.

Let's take a closer look at the different stages of the loop of procrastination:

  1. Procrastination: This is the first stage of the loop, where we put off tasks and responsibilities instead of taking action. We might feel overwhelmed, unsure of where to start, or simply unmotivated.

  2. Guilt and Anxiety: As time passes, we start to feel guilty or anxious about not getting things done. We might worry about the consequences of our inaction or beat ourselves up for not being more productive.

  3. Avoidance and Distraction: To cope with the guilt and anxiety, we might turn to avoidance and distraction. This could involve watching TV, scrolling through social media, or engaging in other activities that provide temporary relief from our negative emotions.

  4. Procrastination (Again): Unfortunately, these avoidance and distraction tactics only serve to prolong the procrastination cycle. We continue to put off tasks and responsibilities, feel guilty and anxious about it, and then turn to avoidance and distraction instead of taking action.

Breaking the loop of procrastination requires intentional effort and a commitment to change. Here are some strategies that can help:

  1. Recognize the loop: The first step in breaking the loop of procrastination is to recognize when you're in it. Pay attention to your thoughts, feelings, and behaviors when you're putting things off and feeling guilty or anxious about it.

  2. Identify triggers: What are the things that tend to trigger your procrastination? Is it a certain type of task or responsibility? Are there particular times of day when you're more likely to procrastinate? Once you identify your triggers, you can take steps to avoid or mitigate them.

  3. Break tasks into smaller steps: Often, the reason we procrastinate is because tasks feel overwhelming. By breaking tasks into smaller, more manageable steps, we can make them feel less daunting and easier to tackle.

  4. Set deadlines: Setting deadlines can help us stay accountable and motivated. Consider setting both short-term and long-term deadlines for tasks and responsibilities.

  5. Practice self-compassion: Be kind to yourself when you're struggling with procrastination. Remember that it's a common struggle and that you're not alone. Practice self-compassion by speaking to yourself kindly and avoiding self-criticism.

Breaking the loop of procrastination takes time and effort, but it's worth it. By taking intentional steps to overcome procrastination, we can improve our productivity, reduce stress and anxiety, and achieve our goals.

jueves, 9 de marzo de 2023

Node js .- Importar Clases.

Node.js es un entorno de programación en JavaScript que se utiliza para construir aplicaciones de servidor. Una de las características más importantes de Node.js es su capacidad para utilizar módulos de JavaScript y paquetes externos. En este artículo, hablaremos sobre cómo se pueden importar clases en Node.js y cómo utilizarlas con un ejemplo de películas.

En Node.js, se pueden importar clases utilizando la palabra clave import. La sintaxis es similar a la utilizada en otros lenguajes de programación modernos. Aquí hay un ejemplo de cómo importar una clase en Node.js:

javascript
import { MyClass } from './my-class.js';

En este ejemplo, MyClass es el nombre de la clase que se está importando desde el archivo my-class.js. La sintaxis { MyClass } indica que solo se está importando la clase MyClass y no cualquier otro valor que pueda estar definido en el archivo.

Ahora que sabemos cómo importar una clase en Node.js, vamos a utilizar un ejemplo de películas para mostrar cómo se puede utilizar una clase importada. Aquí hay una clase Movie que representa una película:

javascript
export class Movie {
  constructor(title, director, language = 'English') {
    this.title = title;
    this.director = director;
    this.language = language;
    this.isPlaying = false;
  }

  play() {
    this.isPlaying = true;
    console.log(`Playing ${this.title}...`);
  }

  pause() {
    this.isPlaying = false;
    console.log(`Paused ${this.title}.`);
  }

  changeLanguage(language) {
    this.language = language;
    console.log(`Changed language to ${language}.`);
  }

  getDetails() {
    return `${this.title} - directed by ${this.director} - ${this.language}`;
  }
}

En este ejemplo, la clase Movie tiene un constructor que toma un título, un director y un idioma como parámetros. También tiene tres métodos nuevos: play(), pause() y changeLanguage(), que permiten reproducir, pausar y cambiar el idioma de la película, respectivamente.

El método play() establece la propiedad isPlaying en true y muestra un mensaje indicando que la película se está reproduciendo. El método pause() establece la propiedad isPlaying en false y muestra un mensaje indicando que la película se ha pausado. El método changeLanguage() actualiza la propiedad language de la película y muestra un mensaje indicando el nuevo idioma seleccionado.

Para utilizar la clase Movie, primero necesitamos importarla en nuestro archivo JavaScript. Aquí hay un ejemplo de cómo se puede hacer esto:

javascript

import { Movie } from './movie.js';

const movie1 = new Movie('The Shawshank Redemption', 'Frank Darabont');
console.log(movie1.getDetails());

movie1.play();
movie1.pause();
movie1.changeLanguage('Spanish');
console.log(movie1.getDetails());

En este ejemplo, estamos importando la clase Movie desde el archivo movie.js. Luego, creamos una instancia de la clase Movie y le pasamos el título, el director y el idioma como parámetros. Finalmente, llamamos a los nuevos métodos play(), pause() y changeLanguage() en la instancia movie1. También imprimimos los detalles actualizados de la película en la consola utilizando el método getDetails().

sábado, 18 de septiembre de 2021

JavaScript.- Objetos I (Explicación básica)

 

                               

Recordemos el uso de una variable , por ejemplo .


let persona = "Erik" ; 

Acabamos de Escribir una variable que guarda un tipo de dato (en este caso texto)

Pero , los objetos los usamos para guardar mas de un dato , sin importar que sean de distintos tipos.

Ejemplo


let persona = {nombre:"Erik"Edad:27sexo:"Masculino"};

Sintaxis

1) se usan {} cuando trabajamos con objetos 

2) : para separar propiedad:valor 

3) cada par propiedad:valor se separa por coma 


Vamos a imprimir el ejemplo en consola.


let persona = {nombre:"Erik"Edad:27sexo:"Masculino"};
console.log(persona)

Hemos logrado guardar en una sola variable varios tipos de datos, ahora se llaman objetos

¿Por qué se llaman Objetos?

Con esta forma de guardar información buscamos una analogía con los objetos de la vida real 

por ejemplo ; 

Un carro , tiene múltiples propiedades como ;  una marca , un color , un tamaño , etc,etc,etc

Entonces , al crear nuestro objeto persona , podemos agregarle las múltiples propiedades y valores para definir de la mejor manera un objeto persona en la vida real.

Esta forma de ver la programación se denomina Programacion Orientada a Objetos

pero , eso lo veremos mas a profundidad despues , mejor vamos a hacer unos arreglos simples al código ya escrito.

1)En lugar de let al declarar objetos por lo general preferimos usar const
2)Separaremos por un salto de linea cada propiedad:valor. 


const persona = {
   nombre:"Erik",
    Edad:27,
     sexo:"Masculino"
   };

console.log(persona)

Aunque el resultado al imprimir en pantalla es el mismo , hemos acomodado el código para identificar 2 cosas , Propiedades y sus valores.

PropiedadValor
nombreErik
Edad27
sexoMasculino


Necesitamos tener esto muy claro para poder acceder a sus propiedades.

Acceder a propiedades del objeto

Por ejemplo , si queremos acceder a la propiedad Edad de nuestro objeto simplemente escribiremos "objeto.propiedad"


const persona = {
   nombre:"Erik",
    Edad:27,
     sexo:"Masculino"
   };

console.log(persona.Edad//objeto.propiedad



practica accediendo a las otras 2 propiedades del ejemplo 

Funciones dentro de un objeto

Un objeto no solo puede contener datos , si no funciones , por ejemplo; una función de una persona, seria poder saludar , asi que , escribamos dentro de nuestro objeto una funcion para saludar utilizando los datos de nuestro objeto.




const persona_Obj = {
   nombre:"Erik",
    Edad:27,
     sexo:"Masculino",
     Saludar: function(){
        return "Hola soy " + persona_Obj.nombre + " y tengo " + persona_Obj.Edad;
     }
   };

console.log(persona_Obj.Saludar()) // objeto.funcion() 




Logramos imprimir en pantalla la función saludar de nuestro objeto , pero  hagamos una pequeña modificación, dentro de la función podemos acceder a las propiedades de nuestro objeto con la palabra reservada this , en lugar de nombrar el objeto.

 nuestro código quedaría así.


const persona_Obj = {
   nombre:"Erik",
    Edad:27,
     sexo:"Masculino",
     Saludar: function(){
        return "Hola soy " + this.nombre + " y tengo " + this.Edad;
     }
   };

console.log(persona_Obj.Saludar()) // objeto.funcion() 


Conclusión


En este articulo , hemos aprendido lo básico sobre objetos y su uso , mas adelante entraremos en profundidad , pero te sugerimos hacer unos ejemplos y practicar , visualizando objetos que hay en tu casa y tratarlos de describirlos en codigo.

Despedida


Esperemos te haya servido de utilidad este articulo , síguenos en nuestras redes sociales para seguir aprendiendo juntos , compártenos cualquier duda o comentario que te haya surgido , puede ayudarnos a crecer a ambos.

TE DEJAMOS UNA imagen que puedes guardar como apuntes de tu progreso.



Oxidative Stress and Sports

 Oxidative stress occurs when there is an imbalance in the body between free radicals and antioxidants. Free radicals are molecules with unp...