Skip to content

Commit a977679

Browse files
authored
Merge branch 'master' into master
2 parents c83da79 + 21d6bca commit a977679

6 files changed

Lines changed: 68 additions & 69 deletions

File tree

01-use-state/Readme.md

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ and can be edited using an **input**.
1818

1919
## Steps
2020

21-
- First we copy the previous example, and do a _npm install_
21+
- First we copy the previous example, and do a _npm install_.
2222

2323
```bash
2424
npm install
@@ -45,14 +45,14 @@ export const MyComponent: React.FC = () => {
4545

4646
- Using the reserved word _export_ we can expose this file to other modules.
4747

48-
- It is not strictly necessary to type it with _React.FC_ (Function Component), but It's a good idea, sticking to _Typescript_ will help us to have
48+
- It is not strictly necessary to type it with _React.FC_ (Function Component), but it's a good idea, sticking to _Typescript_ will help us to have
4949
fewer headaches in the future.
5050

5151
- The component is just a function that returns elements from React.
5252
Notice that in this case we have not added _Props_ since it does not consume any.
5353

5454
- Let's go for the interesting part, surely if we use the Java on Angular
55-
mindset, we would ty implementing something like (**IMPORTANT: THIS IS WRONG**).
55+
mindset, we would ty implementing something the following (**IMPORTANT: THIS IS WRONG**).
5656

5757
```diff
5858
export const MyComponent : React.FC = () => {
@@ -73,13 +73,13 @@ export const MyComponent : React.FC = () => {
7373
If you come to a React project and you come across code like this, it's a bad smell, looks like the person that have coded it did not take the time to learn the basics of this library, let's see why:
7474

7575
- When creating a variable, each time the component is repainted, the value
76-
of the variable _myName_ will always be _John Doe_, why? the component
76+
of the variable _myName_ will always be _John Doe_. Why? the component
7777
is just function that is executed over and over on each repaint.
7878

79-
- If we asign a value directly to the _input_ contro, we are skipping to
79+
- If we asign a value directly to the _input_ we are skipping two
8080
main pillars of React: unidirection flow and asynchronous state assignment.
8181

82-
If you want to see it in action (input not working) you just have to add it to the _app.tsx_ file
82+
If you want to see it in action (input not working) you just have to add it to the _app.tsx_ file.
8383

8484
_./src/app.tsx_
8585

@@ -93,7 +93,7 @@ export const App = () => {
9393
};
9494
```
9595

96-
Ok ... How can I handle this? Using React hooks! Let's take a look to _React.useState_, this hook:
96+
Ok... How can I handle this? Using React hooks! Let's take a look to _React.useState_, this hook:
9797

9898
- Is initialized with a default value.
9999

@@ -110,7 +110,7 @@ have a _setName_ or a _setLastname_?
110110

111111
- Let's go and code this component using _Hooks_.
112112

113-
First we make use of the _setState_
113+
First we make use of the _setState_.
114114

115115
_./src/demo.tsx_
116116

@@ -120,7 +120,7 @@ export const MyComponent: React.FC = () => {
120120
+ const [myName, setMyName] = React.useState('John Doe');
121121
```
122122

123-
- As we have named our _getter_ _myName_ it works for us
123+
- As we have named our _getter_ _myName_, it works for us
124124
to both to display the name in the _h4_, as well as in the
125125
_input_
126126

@@ -130,8 +130,8 @@ export const MyComponent: React.FC = () => {
130130

131131
What do we have here?
132132

133-
- \*_e_: argument of the _eventHandler_, gives us information about the event, exposes a series of properties ..
134-
- **e.target**: which DOM element generated the event.
133+
- \*_e_: argument of the _eventHandler_, gives us information about the event, exposes a series of properties.
134+
- **e.target**: which DOM Element generated the event.
135135
- **e.target.value**: what value does this element have (the value property
136136
of the DOM Element that generated the event).
137137

@@ -149,15 +149,15 @@ arguments and pass it to the _myName_ _setState_ function.
149149

150150
How is going to work?
151151

152-
- _setMyName_ request update the state.
152+
- _setMyName_ requests to update the state.
153153
- This will launch a rerender of the component.
154154
- When the component code is executed and reaches the line
155155
code that does the _useState_ instead of return _John Doe_, it will
156156
will supply the name that was stored with _setState_
157157
- When rerendering the component that new value will be shown in the
158158
screen.
159159

160-
You have to change your mindset, ... try to repeat this example
160+
You have to change your mindset, try to repeat this example
161161
without help and understand it well, it is your first big step to understand
162162
how this technology works.
163163

01-use-state/Readme_es.md

Lines changed: 27 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,17 @@ un **h4**, y por otro permita editarlo utilizando un **input**.
1919

2020
## Paso a Paso
2121

22-
- Primero copiamos el ejemplo anterior, y hacemos un _npm install_
22+
- Primero copiamos el ejemplo anterior y hacemos un _npm install_
2323

2424
```bash
2525
npm install
2626
```
2727

28-
- Vamos a crear un fichero que llamaremos _demo.tsx_, vayamos paso a paso
29-
primero nos importamos **React** ¿Por qué si de primeras no uso nada que
30-
ponga _React._ porque en el momento que empezamos a poner tsx/jsx
31-
(es decir esos _h1_, _input_ o _div_ que después se traducen a
32-
_React.createElement_ es necesario importarlo).
28+
- Vamos a crear un fichero que llamaremos _demo.tsx_. Vayamos paso a paso:
29+
primero nos importamos **React**. ¿Por qué si de primeras no uso nada que
30+
ponga _React_? porque en el momento que empezamos a poner tsx/jsx
31+
(es decir, esos _h1_, _input_ o _div_ que después se traducen a
32+
_React.createElement_) es necesario importarlo.
3333

3434
_demo.tsx_
3535

@@ -51,11 +51,11 @@ export const MyComponent: React.FC = () => {
5151
- No es extrictamente necesario tiparlo con _React.FC_ (Function Component), pero
5252
es buena idea, todo lo que nos atemos a _Typescript_ nos servirá para tener
5353
menos dolores de cabeza en el futuro.
54-
- El componente no es más que una functiona que devuelve elementos de React.
54+
- El componente no es más que una función que devuelve elementos de React.
5555
Fijate que en este caso no hemos puesto _Props_ ya que no consume ninguna
5656
del exterior.
5757

58-
- Vamos a por la parte interesante, seguro que nuestra mente Java on Angular
58+
- Vamos a por la parte interesante, seguro que nuestra mente Java o Angular
5959
nos mueve a implementar lo siguiente (**IMPORTANTE: ESTO ESTA MAL**).
6060

6161
```diff
@@ -76,7 +76,7 @@ export const MyComponent : React.FC = () => {
7676

7777
Si llegáis a un proyecto React y os encontráis código como este, huele a que los
7878
que lo han codificado no se tomaron el tiempo de aprender las bases de esta
79-
librerías, veamos porque:
79+
librerías, veamos por qué:
8080

8181
- Al crear una variable, cada vez que se vuelva a repintar el componente
8282
_myName_ va a valer siempre _John Doe_, esto no deja de ser una función que se
@@ -86,7 +86,7 @@ librerías, veamos porque:
8686
dos de los pilares de React, el flujo unidireccional, y que el seteo del
8787
estado sea asíncrono.
8888

89-
Si queréis verlo en acción sólo tenéis que añadirlo al fichero _app.tsx_
89+
Si queréis verlo en acción sólo tenéis que añadirlo al fichero _app.tsx_.
9090

9191
_./src/app.tsx_
9292

@@ -100,8 +100,8 @@ export const App = () => {
100100
};
101101
```
102102

103-
Vale... ¿Cómo puedo manejar esto? ¡ Con los hooks de React ! Tenemos
104-
_React.useState_
103+
Vale... ¿Cómo puedo manejar esto? ¡Con los hooks de React! Tenemos
104+
_React.useState_.
105105

106106
- Se inicializa con un valor por defecto.
107107

@@ -114,15 +114,15 @@ _React.useState_
114114
nuestro _getter_ y el segundo nuestro \_setter.
115115

116116
¿Por qué narices usa un array? Aquí viene la genialidad, si hubiese devuelto
117-
un objeto, al hacer destructuring del objeto habríamos tenido que cenirños
117+
un objeto, al hacer destructuring del objeto habríamos tenido que ceñirnos
118118
a un nombre concreto de getter y a uno de setter, esto es un rollo porque
119-
en un componente podemos tener multiples state, y además queremos añadirle
120-
sentido a los nombres, ¿Porque tener un _setState_ genérico cuando podemos
119+
en un componente podemos tener múltiples state, y además queremos añadirle
120+
sentido a los nombres, ¿Por qué tener un _setState_ genérico cuando podemos
121121
tener un _setName_ o un _setLastname_?
122122

123-
- Vamos a montar este componente con _Hooks_
123+
- Vamos a montar este componente con _Hooks_.
124124

125-
Primero hacemos uso del _setState_
125+
Primero hacemos uso del _setState_:
126126

127127
_./src/demo.tsx_
128128

@@ -134,20 +134,20 @@ export const MyComponent: React.FC = () => {
134134

135135
- Como hemos nombrado a nuestro _getter_ _myName_ nos vale
136136
tanto para mostrar el nombre en el _h4_, así como en el
137-
_input_
137+
_input_.
138138

139139
- Ahora viene la parte interesante, para poder capturar cuando
140140
el usuario teclea en el input nos suscribimos al evento
141141
_onChange_ (este es un evento estándar de HTML, más info [MDN](https://developer.mozilla.org/es/docs/Web/API/HTMLElement/change_event)).
142142

143-
¿ Qué tenemos aquí?
143+
¿Qué tenemos aquí?
144144

145-
- \*_e_: argumento del _eventHandler_, nos da información del evento, expone una serie de propiedades..
146-
- **e.target**: que DOM elemento genero el evento.
145+
- \*_e_: argumento del _eventHandler_, nos da información del evento, expone una serie de propiedades:
146+
- **e.target**: qué DOM Element generó el evento.
147147
- **e.target.value**: que valor tiene ese elemento (la propiedad valor
148-
del DOM Element que genero el evento).
148+
del DOM Element que generó el evento).
149149

150-
En este event handler aprovecha os para recojer el valor del input y pedir
150+
En este event handler aprovechamos para recoger el valor del input y pedir
151151
setear el estado de _myName_.
152152

153153
```diff
@@ -161,17 +161,17 @@ setear el estado de _myName_.
161161

162162
¿Qué va a provocar esto?
163163

164-
- Que la petición _setMyName_ actualize el estado.
164+
- Que la petición _setMyName_ actualice el estado.
165165
- Esto va a lanzar un repintado del componente.
166166
- Cuando se ejecute el código del componente y llegue a la línea
167-
de código que hace el _useState_ en vez de _John Doe_ se le
167+
de código que hace el _useState_, en vez de _John Doe_ se le
168168
facilitará el nombre que se almaceno con _setState_
169-
- Al repintar el componente se usara ese nuevo valor mostrandolo
169+
- Al repintar el componente se usará ese nuevo valor mostrandolo
170170
por pantalla.
171171

172172
Es un cambio de mentalidad grande,... intenta repetir este ejemplo
173173
sin ayuda y entenderlo bien, es tu primer gran paso para entender
174-
como funciona esta tecnología.
174+
cómo funciona esta tecnología.
175175

176176
# ¿Te apuntas a nuestro máster?
177177

02-use-state-object/Readme.md

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,21 @@
1313

1414
This example takes the [_01-use-state_](https://github.com/Lemoncode/react-hooks-by-example/blob/master/01-use-state) as a starting point.
1515

16-
In the previous example we stored a string in the state, but
17-
...do we need to use a _useState_ per each basic fild, can we store an object using
18-
useState? Yes you can, but we have to take into consideration that updates on this
16+
In the previous example we stored a string in the state, but... we don't use _useState_ just for basic types. Can we store an object using
17+
_useState_? Yes we can, but we have to take into consideration that updates on this
1918
object must be done following the principle of immutability (we never
2019
add an update on a given object, we create a new one).
2120

2221
## Steps
2322

24-
- First we copy the previous example, and execute a _npm install_
23+
- First we copy the previous example, and execute a _npm install_.
2524

2625
```bash
2726
npm install
2827
```
2928

3029
- Let's go store in the state an object that has the name
31-
and last name of a given user, we can write something like:
30+
and last name of a given user. We can write something like:
3231

3332
_./src/demo.tsx_
3433

@@ -41,9 +40,9 @@ export const MyComponent: React.FC = () => {
4140
+ });
4241
```
4342

44-
By doing this we create a state that stores the object, but it would a good idea to
45-
get benefit of using TypeScript and add strong typing, this will help us finding silly bugs
46-
like _Ouch ! I forgot to type the "t" in lastname_.
43+
By doing this we create a state that stores the object, but it would be a good idea to
44+
get benefit of using TypeScript and add strong typing. This will help us finding silly bugs
45+
like _Ouch! I forgot to type the "t" in lastname_.
4746

4847
```diff
4948
+ interface UserInfo {
@@ -59,7 +58,7 @@ export const MyComponent: React.FC = () => {
5958
});
6059
```
6160

62-
- Coold, now that we got our object stored and typed, let's display the user name and lastname.
61+
- Cool, now that we have our object stored and typed, let's display the user's name and lastname.
6362

6463
```diff
6564
return (
@@ -71,9 +70,9 @@ export const MyComponent: React.FC = () => {
7170
);
7271
```
7372

74-
If we start the application we can see how the name and surname are displayed.
73+
If we start the application we can see how the name and lastname are displayed.
7574

76-
- Let's jump on the main thing, updating the name field..., we might be tempted to update userInfo, but this won't
75+
- Let's jump on the main thing, updating the name field... We might be tempted to update userInfo, but this won't
7776
work, anyway let's give a try (**SPOILER ALERT: THIS IS WRONG**):
7877

7978
```diff
@@ -94,8 +93,8 @@ This is not going to work, we are again applying a Java / Angular approach,
9493
we are trying to modify something that is alive only when the function is being
9594
executed, once the component is rerended this value will be lost.
9695

97-
- The way to do this is by creating a new objecto and assigning it using the _setState_
98-
method, in order to do this copy we use the spread operator (by doing this all the fields
96+
- The way to do this is by creating a new object and assigning it using the _setState_
97+
method. In order to do this copy we use the spread operator (by doing this, all the fields
9998
that doesn't change are just passed as they are, they are not recreated).
10099

101100
```diff
@@ -153,7 +152,7 @@ entry for the one that had changes.
153152
```
154153

155154
Now we can test and see that we can update both the name and
156-
surname.
155+
lastname.
157156

158157
# About Basefactor + Lemoncode
159158

02-use-state-object/Readme_es.md

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,15 @@
1414

1515
Este ejemplo toma como punto de partida el ejemplo [_01-use-state_](https://github.com/Lemoncode/react-hooks-by-example/blob/master/01-use-state).
1616

17-
En el ejemplo anterior almacenabamos un string en el estado, pero
18-
no todo son tipos básicos, ¿Podemos almacenar un objeto utilizando
19-
useState? Claro que sí, lo único que cuando queremos introducir
17+
En el ejemplo anterior almacenábamos un string en el estado, pero
18+
no todo son tipos básicos. ¿Podemos almacenar un objeto utilizando
19+
_useState_? Claro que sí, lo único que cuando queremos introducir
2020
cambios en el estado tenemos que seguir el principio de inmutabilidad
2121
y no modificar el objeto original.
2222

2323
## Paso a Paso
2424

25-
- Primero copiamos el ejemplo anterior, y hacemos un _npm install_
25+
- Primero copiamos el ejemplo anterior, y hacemos un _npm install_.
2626

2727
```bash
2828
npm install
@@ -43,8 +43,8 @@ export const MyComponent: React.FC = () => {
4343
```
4444

4545
Así creamos un estado al que le almacenamos el objeto, pero nos vendría
46-
bien tener algo de strong typing, que nos ayude a encontrar fallos tontos
47-
del tipo me olvide poner la "t" en lastname.
46+
bien tener algo de strong typing que nos ayude a encontrar fallos tontos
47+
del tipo _me olvide poner la "t" en lastname_.
4848

4949
```diff
5050
+ interface UserInfo {
@@ -73,10 +73,10 @@ export const MyComponent: React.FC = () => {
7373
);
7474
```
7575

76-
- Si arrancamos la aplicación podemos ver como se muestra el nombre y apellido.
76+
- Si arrancamos la aplicación podemos ver cómo se muestra el nombre y apellido.
7777

7878
- Ahora vamos al turrón, podríamos estar tentados de modificar directamente userInfo y
79-
ver que pasa, hacer algo así como (**SPOILER ALERT: ESTO ESTA MAL**):
79+
ver qué pasa, hacer algo así como (**SPOILER ALERT: ESTO ESTA MAL**):
8080

8181
```diff
8282
return (
@@ -120,13 +120,13 @@ que vamos a introducir una modificación.
120120
);
121121
```
122122

123-
Ahora sí que funciona, cuando queremos actualizar _userInfo_ hacemos
123+
Ahora sí que funciona. Cuando queremos actualizar _userInfo_ hacemos
124124
la petición para actualizar el estado y le creamos un objeto nuevo
125-
copiando todas las propiedades del antiguo y como último pasa machacamos
125+
copiando todas las propiedades del antiguo y, como último paso, machacamos
126126
el valor de la propiedad que ha cambiado.
127127

128128
- Vamos a hacer lo mismo para lastname, si quieres dale a la pausa en este
129-
video e intentalo tu por tu cuenta.
129+
video e inténtalo tu por tu cuenta.
130130

131131
```diff
132132
return (

Readme.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,15 @@ Set of step by step guide examples covering React Hooks, from start to advanced
1717

1818
About this examples:
1919

20-
- Each example is focused in a topic (simple and straightforward).
21-
- Each example contains a Readme.md with an step by step guide to reproduce it.
20+
- Each example is focused on a topic (simple and straightforward).
21+
- Each example contains a Readme.md with a step by step guide to reproduce it.
2222

2323
# Examples implemented
2424

2525
List of examples:
2626

2727
- [00-boiler-plate](https://github.com/Lemoncode/react-hooks-by-example/tree/master/00-boilerplate): starting point, just a blank create-react-app project (all examples will take
28-
this as starting point)
28+
this as starting point).
2929
- [01-use-state](https://github.com/Lemoncode/react-hooks-by-example/tree/master/01-use-state): adding state (simple element) to a functional component.
3030
- [02-use-state-object](https://github.com/Lemoncode/react-hooks-by-example/tree/master/02-use-state-object): adding state (object) to a functional component.
3131
- [03-component-did-mount](https://github.com/Lemoncode/react-hooks-by-example/tree/master/03-component-did-onload): executing some operations when a functional component gets mounted.

0 commit comments

Comments
 (0)