teleren/devto huggingface dataset:
Learn useState and useRef from simple example
Tags: webdev, beginners, react
Published: 2023-03-27 19:12:43

React is a popular JavaScript library for building user interfaces. One of the key features of React is its use of hooks, which allow developers to manage state and perform side effects in functional components. In this article, we'll explore two of the most commonly used hooks: useRef and useState.

useRef is a hook that returns a mutable ref object that can be used to store a value that persists between renders. useState is a hook that returns a state variable and a function to update that variable.

Let's take a look at a simple example that demonstrates how to use both useRef and useState in a React component:

In this example, we define a component called Example that uses both useState and useRef hooks.

First, we define a state variable count using the useState hook. We also define a ref called inputRef using the useRef hook.

Inside the handleButtonClick function, we update the state of count using the setCount function, which increments the count by 1 each time the button is clicked. We also use the focus method of the inputRef to set the focus on the text input field.

Finally, we render the current value of count using an HTML paragraph element and an input field that is assigned the inputRef ref. We also render a button that calls the handleButtonClick function when clicked.

This simple example demonstrates how we can use both useState and useRef hooks in a React component to manage state and references to DOM elements.

useRef can be particularly useful for managing references to DOM elements that need to persist between renders. For example, if you need to programmatically set focus on an input field when a button is clicked, you can use useRef to store a reference to that input field and then call its focus method in an event handler.

useState, on the other hand, is useful for managing state that changes over time. Whenever you need to store a value that can change based on user interactions or other factors, you can use useState to define a state variable and an associated updater function.

Overall, useRef and useState are powerful tools that can help you build more robust and dynamic React components. By leveraging these hooks, you can more easily manage state and references to DOM elements, allowing you to create more responsive and interactive user interfaces.

```
import React, { useRef, useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);
  const inputRef = useRef(null);

  const handleButtonClick = () => {
    setCount(count + 1);
    inputRef.current.focus();
  };

  return (
    <div>
      <p>You clicked {count} times</p>
      <input type="text" ref={inputRef} />
      <button onClick={handleButtonClick}>Click me</button>
    </div>
  );
}

```
La importancia de ser ordenado
Tags: beginners, programming, productivity, go
Published: 2023-03-27 19:03:23

Hola Developer, hoy quiero hablarte algo que, en mi opinión, es muy importante cuando se trabaja en equipo y aunque parezca una tontería es de suma importancia.

La organización y estructuración adecuada de los archivos y carpetas de un proyecto de desarrollo de una aplicación es esencial para asegurar su eficiencia y mantenibilidad a largo plazo. No utilizar una estructura de carpetas estándar puede llevar a una complejidad innecesaria y dificultades para el equipo de desarrollo, especialmente cuando se trabaja en proyectos complejos con múltiples desarrolladores.

Aquí hay algunas razones por las que no usar una estructura de carpetas estándar puede ser problemático:

* Confusión en la ubicación de archivos: Sin una estructura de carpetas clara y consistente, puede ser difícil para los miembros del equipo de desarrollo encontrar los archivos y recursos que necesitan. Esto puede llevar a errores de versionamiento y a la creación de duplicados innecesarios, lo que dificulta el seguimiento de los cambios y la resolución de conflictos.

* Dificultad en la colaboración: Cuando varios desarrolladores están trabajando en un proyecto sin una estructura de carpetas común, pueden surgir problemas de colaboración. Cada desarrollador puede organizar sus archivos de manera diferente, lo que dificulta la integración de sus cambios en el proyecto global. Esto puede causar retrasos en el desarrollo y aumentar el tiempo necesario para resolver conflictos.

* Dificultades en la escalabilidad: Cuando un proyecto comienza a crecer en tamaño y complejidad, la falta de una estructura de carpetas estándar puede llevar a una mayor complejidad y confusión. Con más archivos y recursos que manejar, el equipo de desarrollo puede perder tiempo tratando de encontrar los archivos que necesitan y comprender cómo están organizados los recursos.

* Problemas de mantenimiento: Sin una estructura de carpetas consistente, puede ser difícil realizar cambios en el proyecto y mantenerlo actualizado. Los desarrolladores pueden tener dificultades para identificar los archivos y recursos que necesitan modificar y pueden introducir errores sin darse cuenta. Esto puede llevar a problemas de calidad y a la necesidad de hacer cambios adicionales para corregir los errores.

En resumen, no utilizar una estructura de carpetas estándar puede crear problemas significativos para el equipo de desarrollo de una aplicación. La organización adecuada de los archivos y recursos del proyecto es esencial para garantizar la eficiencia y la mantenibilidad a largo plazo. Por lo tanto, es importante que los equipos de desarrollo adopten una estructura de carpetas consistente y estandarizada desde el principio del proyecto. Esto ayudará a evitar problemas de colaboración, confusión en la ubicación de archivos, dificultades en la escalabilidad y problemas de mantenimiento en el futuro.

Aquí te dejo un video en el que te explico como estructurar un proyecto de Go, explicando para qué sirve cada carpeta:

{% embed https://youtu.be/T2SqbY2SMvU %}
Making of Among Us in Discord - DEVLBOG 7 - We're Starting the Games soon...?
Tags: 100daysofcode, python, discord, gamedev
Published: 2023-03-27 18:45:36

{% embed https://twitter.com/MrStiK101/status/1640423107499311113?s=20 %}

Heya, this is Mr.StiK

So, as you can see, on the tweet, we did something, again, bit small stuff... we just started on the game concepts, which kind of leading me to a confusion...

Should I change the code? If you don't know what I mean, let me explain;

You see, the code for the bot is like as if anyone can mess any games from ANY server... I have not wrote the code in the way in which multiple server can start separate games with no problems... so, I'll be considering advices from veteran 'pythonists' for some answers...

But again, that's for later, my exam's are almost getting over, report card and fate coming soon (XD)

`Sorry, there's no code for you today, just want to say I'm still alive -_-`

So, yeah, that's it.

Toodles!
Making a auth system in SECONDS with Authflow!
Published: 2023-06-12 17:18:01

---
title: Making a auth system in SECONDS with Authflow!
published: true
date: 2023-03-27 18:40:39 UTC
tags: 
canonical_url: 
---

 **Let's be honest, making secure authentication systems is HARD.** Really hard. You need to think of security, compatibility, ease-of-use, and much more. It can take days, if not weeks, to develop an authentication system that meets all these requirements. _But what if I told you there was a way to implement a secure and easy-to-use authentication system in just a few ~~minutes~~ _ **_seconds\*_**?\*

> Using node? I have a project for you to fork! Scroll down a bit

Introducing Authflow a simple and straightforward way to add authentication to your website. With Authflow, you can implement a login system in just a few steps, without worrying about the security and compatibility issues that often arise when developing your own system from scratch.

How does Authflow work? First, you redirect your users to the Authflow login flow. Then, Authflow loads the "Continue with Google" button on their website. The user logs in, and their information is sent back to an intermediary page on your website, where it is stored in cookies. Finally, the user is redirected to the "logged in" page. It's that simple.

To get started with Authflow, all you need to do is add the following script to your website:

```
<script src="https://jscdn.glitch.me/cdn/authflow.js" crossorigin="anonymous"></script>

```

And then, initiate the login process using the following code:

```
authflow.login({
  app_name: "App name",
  redirect: "your_redirect_url",
});

```

That's it! With just a few lines of code, you can implement a secure and easy-to-use login system on your website.

But that's not all. Authflow also offers some additional features that you can use to further enhance your authentication system. For example, with the Authflow Button API, you can create a simple login button on your website. And with Authflow Instant, you can quickly and easily add a login with Google button to your page, providing a convenient way for users to log in.

**<mark>And this is really useful:</mark>** If you're using Node.js, you can use the "Zarran API" to create your own authentication and authorization server. It has many features built-in, plus there's also a password-username login if your users don't have a Google account. ~~(btw, who doesn't?)~~

Get started now at [https://authflow.glitch.me/](https://authflow.glitch.me/)!
Go from one screen to another in SwiftUI
Tags: 100daysofcode, swift, swiftu, ios
Published: 2023-03-27 18:33:12

In this post we will be explore how can we navigate from one screen to another using the NavigationLink

```
import SwiftUI


struct ContentView: View {
    var body: some View {
        NavigationView {
            List(1..<30){ row in
                NavigationLink{
                    Text("Details \(row)")
                } label: {
                    Text("Row \(row)")
                }
                
            }
            .navigationTitle("SwiftUI")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
```
**Output**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gkwz172ix720dw9alljs.gif)
12 berufliches Vorwärtskommen: Wie du nachsichtiger sein kannst.
Tags: deutsch, career, austausch, 1min
Published: 2023-03-27 18:14:00

Moin Moin,

üben ist der offensichtliche Schlüssel, um nachsichtiger zu sein. Genau dafür soll es eine wichtige Anregungen geben:

> Sei nachsichtig mit dir selbst im Nachsichtigsein.

Neigst du dazu streng mit dir selbst zu sein ?  Besonders, wenn du etwas neues lernst ?

Habe verzeihendes Verständnis ( [Nachsicht↗](https://www.dwds.de/wb/Nachsicht) ) mit dir selbst, solange du ernsthaft anstrebst nachsichtiger zu sein und es dir manchmal nicht gelingt.
Das gibt dir Kraft, um auch nachsichtiger mit anderen zu sein.

Hast du auch einen Tipp zum Nachsichtigsein ?
Oder einen Tipp für eine andere Charakter-Eigenschaft ?

Beste Grüße,
Mustafa
How to Use the useState Hook to Show/Hide Content in React
Tags: react, usestate, hooks, frontend
Published: 2023-03-27 17:52:15

 When building a React web application, you may want to show or hide content based on user interaction. A common way to accomplish this is to use a button that toggles the visibility of the content. In this article, we'll show you how to use the useState hook to implement a button to show/hide content in React.

**The useState Hook**

The useState hook is a built-in hook in React that allows us to add state to a functional component. With useState, we can create a state variable and a function to update that variable. Whenever the state variable is updated, React will automatically re-render the component to reflect the new state.

To use useState, we first need to import it from the React library:

```
import React, { useState } from 'react';

```

Then, we can call useState and pass in an initial value for the state variable:

```
const [isVisible, setIsVisible] = useState(false);

```
In this example, we're setting the initial value of _isVisible_ to false, indicating that the content should be hidden by default. We're also using array destructuring to create two variables: _isVisible_, which holds the current value of the state variable, and _setIsVisible_, which is a function that updates the state variable.

**Toggling the Content**

Now that we have a way to keep track of whether the content should be shown or hidden, we can use the _isVisible_ state variable to conditionally render the content in our component.

To do this, we can use a conditional statement to check whether _isVisible_ is true or false, and render the content accordingly:

```
return (
  <div>
    <button onClick={() => setIsVisible(!isVisible)}>
      {isVisible ? 'Hide content' : 'Show content'}
    </button>
    {isVisible && (
      <div>
        <p>This is the content to show/hide.</p>
      </div>
    )}
  </div>
);

```

In this example, we're rendering a button that toggles the _isVisible_ state when clicked. We're also using a conditional statement to render the content only if _isVisible_ is true. If _isVisible_ is false, the content will not be rendered.

> full code

```
import React, { useState } from 'react';

function ShowHideContent() {
  const [isVisible, setIsVisible] = useState(false);

  return (
    <div>
      <button onClick={() => setIsVisible(!isVisible)}>
        {isVisible ? 'Hide content' : 'Show content'}
      </button>
      {isVisible && (
        <div>
          <p>This is the content to show/hide.</p>
        </div>
      )}
    </div>
  );
}

export default ShowHideContent;

```

**Conclusion**

In this article, we've shown you how to use the _useState _hook to show/hide content in React. By creating a state variable to keep track of whether the content should be visible, and conditionally rendering the content based on the state variable, we can create a simple and effective way to toggle the visibility of content in our React components.
Deploy Static Website Using S3 Bucket
Tags: bytewise, 100daysofcode, aws, staticwebapps
Published: 2023-03-27 17:43:06

**Step # 1:**
- Search for S3 in the search bar of console and select the first option.

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

**Step # 2:**
- Create a bucket using the option available as shown below.

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

**Step # 3:**
- Write down the name of the bucket. In the object ownership select the ACLs enabled. Scroll below and unchecked the block all public access.

**Step # 4:**
- In the upload section, upload the static website files, in my case I have a wave website files.

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

**Step # 5:**
- Now go to the property section and scroll to the down and enable the static website hosting, as shown below:

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

**Step # 6:**
- Now go to the permissions section and generate a policy for the particular website and update the policy in order to deploy and render the website successfully.

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

**Step # 7:**
- Now go the property section again and scroll down and select the link for the website, copy the link and open new tab, paste the link and hit enter, here we see magic because our website is deployed and ready to run on the aws server. 
Here is the link for the deployed website.
Link: http://myfirstwaveweb.s3-website-us-east-1.amazonaws.com/
*CodeNewbie* Meme Monday
Tags: codenewbie, beginners, career
Published: 2023-03-27 17:37:40

Hey y'all it's **CodeNewbie Meme Monday**! Woooo! We are happy to see you again over here on the DEV Community. 

As always, this is a humble call for NEWBIE-related memes! Drop your beginner-related, job-related, starting-a-new-career-related memes below! 

AND if it is your first time here welcome! Happy to have you in the thread!
local git server - platformIO
Tags: git, vscode, platformio
Published: 2023-03-27 17:36:48

Hi to all,

After hours of searching without finding a solution I try here.
I am programming with platformIO IDE mostly in C++
My workstation is a MAC, VS code with platformIO extension and git installed

Some Linux Debian Server running under VMware one of them git installed

Localy everything is fine, git works on the command line and from platformIO/VSCode

On the server git works fine from the command line.

What I am looking for is to upload my projects to the git server, as backup and to become familar with that to have more know how if I want do upload projects to git hub.

If I try to do this VS code will always upload / clone to git, but how can I manage to upload clone to my server.

Regards

Rainer
What A Promise ! '1st'
Tags: javascript, beginners, programming, tutorial
Published: 2023-03-27 17:31:43

### Hoo-AH , In this CODE CAPSULE we will go throw Promises in js and learn how to use it , all codes will be in one Js file with examples and results, So,enough videos just take 5 mins to read it.<br />

---

##What is Promise in JS ?<br />
<br />
>A Promise is a very useful Object helper to work with **Asynchronous** Tasks and It's protector from the callback hell !

---


### let's say we have code that do some magic and that magic is depend on server response , in this case **Promises** give us the advantage of complete our code execution without waiting for the server response , and make a part of our code execite when the result fullfilld ot failed 


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


 Here we create a promise with Promise Constructor function


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


Adding function as Executor as an argumnent for 
Promise Constructor function and this executor takes two arguments Resolve in case of success and reject in case of fail . 

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


we create a time interval to simulate as a server response after a while, then we will resolve the value .
 

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

Now , we will log the value after 1500ms or '1.5' seconds to the console and it will be **"Done"**

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


##See u in another CodeCapsule !
Three JS Examples : 1. Three JS Cube Animation
Tags: threejs, webdev, design, css
Published: 2023-03-27 17:25:00

Three.js is a cross-browser JavaScript library and application programming interface used to create and display animated 3D computer graphics in a web browser using WebGL.  

[Three js docs](https://threejs.org/docs/)

---
{% link https://dev.to/flagrede/making-a-2d-rpg-game-with-react-tree-fiber-4af1 %}

---

## Three JS Cube Animation
---

{% youtube aDgIzSflvR4 %}


 ---
### [Source code](https://democoding.netlify.app/threejs/three-js-cube-animation)

---

## How to use Three JS in React JS

React-three-fiber is a React renderer for three.js


### Installing react-three-fiber



```bash
npm install three @react-three/fiber 
```

### Create your first geometry 

```jsx
import { createRoot } from 'react-dom/client'
import React, { useRef, useState } from 'react'
import { Canvas, useFrame } from '@react-three/fiber'

function Box(props) {
  // This reference gives us direct access to the THREE.Mesh object
  const ref = useRef()
  // Hold state for hovered and clicked events
  const [hovered, hover] = useState(false)
  const [clicked, click] = useState(false)
  // Subscribe this component to the render-loop, rotate the mesh every frame
  useFrame((state, delta) => (ref.current.rotation.x += delta))
  // Return the view, these are regular Threejs elements expressed in JSX
  return (
    <mesh
      {...props}
      ref={ref}
      scale={clicked ? 1.5 : 1}
      onClick={(event) => click(!clicked)}
      onPointerOver={(event) => hover(true)}
      onPointerOut={(event) => hover(false)}>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
    </mesh>
  )
}

createRoot(document.getElementById('root')).render(
  <Canvas>
    <ambientLight />
    <pointLight position={[10, 10, 10]} />
    <Box position={[-1.2, 0, 0]} />
    <Box position={[1.2, 0, 0]} />
  </Canvas>,
)

```
### Output 

![Live Demo](https://camo.githubusercontent.com/7f08d0e6e154fd30f3b6aa91e04e56f520f983a17b3250080321b3ec456d8bbd/68747470733a2f2f692e696d6775722e636f6d2f7353344172725a2e676966)

---
## For more information

1. Check my GitHub profile
[https://github.com/amitSharma7741](https://github.com/amitSharma7741)

2. Subscribe my Youtube Channel 
[https://www.youtube.com/@democode](https://www.youtube.com/@democode) 

3. Check out my Fiver profile if you need any freelancing work
[https://www.fiverr.com/amit_sharma77](https://www.fiverr.com/amit_sharma77)

4. Follow me on Instagram
[https://www.instagram.com/fromgoodthings/](https://www.instagram.com/fromgoodthings/)

5. Check out my Facebook Page 
[Programming memes by Coder](https://www.facebook.com/programmingmemesbycoders)

6. Linktree
[https://linktr.ee/jonSnow77](https://linktr.ee/jonSnow77)

 

---
---

{% instagram CoukQjbuwW3 %}