You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The <em>createSlice</em> function's <em>name</em> parameter defines the prefix which is used in the action's type values. For example, the <em>createNote</em> action defined later will have the type value of <em>notes/createNote</em>. It is a good practice to give the parameter a value which is unique among the reducers. This way there won't be unexpected collisions between the application's action type values. The <em>initialState</em> parameter defines the reducer's initial state. The <em>reducers</em> parameter takes the reducer itself as an object, of which functions handle state changes caused by certain actions. Note that the <em>action.payload</em> in the function contains the argument provided by calling the action creator:
517
+
The <em>createSlice</em> function's <em>name</em> parameter defines the prefix which is used in the action's type values. For example, the <em>createNote</em> action defined later will have the type value of <em>notes/createNote</em>. It is a good practice to give the parameter a value which is unique among the reducers. This way there won't be unexpected collisions between the application's action type values.
518
+
The <em>initialState</em> parameter defines the reducer's initial state.
519
+
The <em>reducers</em> parameter takes the reducer itself as an object, of which functions handle state changes caused by certain actions. Note that the <em>action.payload</em> in the function contains the argument provided by calling the action creator:
518
520
519
521
```js
520
522
dispatch(createNote('Redux Toolkit is awesome!'))
521
523
```
522
524
523
-
This dispatch call responds to dispatching the following object:
525
+
This dispatch call is equivalent to dispatching the following object:
524
526
525
527
```js
526
528
dispatch({ type:'notes/createNote', payload:'Redux Toolkit is awesome!' })
@@ -542,7 +544,7 @@ createNote(state, action) {
542
544
543
545
We are mutating <em>state</em> argument's array by calling the <em>push</em> method instead of returning a new instance of the array. What's this all about?
544
546
545
-
Redux Toolkit utilizes the [Immer](https://immerjs.github.io/immer/) library with reducers created by <em>createSlice</em> function, which makes it possible to mutate the <em>state</em> argument inside the reducer. Immer uses the mutated state to produce a new, immutable state and thus the state changes remain immutable. Note that <em>state</em> can be changed without "mutating" it, as we have done with the <em>toggleImportanceOf</em> action. In this case, the function <i>returns</i> the new state. Nevertheless mutating the state will often come in handy especially when a complex state needs to be updated.
547
+
Redux Toolkit utilizes the [Immer](https://immerjs.github.io/immer/) library with reducers created by <em>createSlice</em> function, which makes it possible to mutate the <em>state</em> argument inside the reducer. Immer uses the mutated state to produce a new, immutable state and thus the state changes remain immutable. Note that <em>state</em> can be changed without "mutating" it, as we have done with the <em>toggleImportanceOf</em> action. In this case, the function directly <i>returns</i> the new state. Nevertheless mutating the state will often come in handy especially when a complex state needs to be updated.
546
548
547
549
The <em>createSlice</em> function returns an object containing the reducer as well as the action creators defined by the <em>reducers</em> parameter. The reducer can be accessed by the <em>noteSlice.reducer</em> property, whereas the action creators by the <em>noteSlice.actions</em> property. We can produce the file's exports in the following way:
548
550
@@ -653,9 +655,9 @@ The following is printed to the console
653
655
654
656

655
657
656
-
The output is interesting but not very useful. This is about the previously mentioned Immer library used by the Redux Toolkit, which is now used internally to save the state of the Store.
658
+
The output is interesting but not very useful. This is about the previously mentioned Immer library used by the Redux Toolkit internally to save the state of the Store.
657
659
658
-
The status can be converted to a human-readable format, e.g. by converting it to a string and back to a JavaScript object as follows:
660
+
The status can be converted to a human-readable format, e.g. by converting it first to a string and then back to a JavaScript object as follows:
@@ -669,13 +671,13 @@ Console output is now human readable
669
671
670
672
[Redux DevTools](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd) is a Chrome addon that offers useful development tools for Redux. It can be used for example to inspect the Redux store's state and dispatch actions through the browser's console. When the store is created using Redux Toolkit's <em>configureStore</em> function, no additional configuration is needed for Redux DevTools to work.
671
673
672
-
Once the addon is installed, clicking the <i>Redux</i> tab in the browser's console should open the development tools:
674
+
Once the addon is installed, clicking the <i>Redux</i> tab in the browser's developer tools, the Redux DevTools should open:
673
675
674
676

675
677
676
678
You can inspect how dispatching a certain action changes the state by clicking the action:
677
679
678
-

680
+

679
681
680
682
It is also possible to dispatch actions to the store using the development tools:
681
683
@@ -691,19 +693,19 @@ You can find the code for our current application in its entirety in the <i>part
691
693
692
694
Let's continue working on the anecdote application using Redux that we started in exercise 6.3.
693
695
694
-
#### 6.10 Better anecdotes, step8
696
+
#### 6.10 Better Anecdotes, step 8
695
697
696
698
Install Redux Toolkit for the project. Move the Redux store creation into the file <i>store.js</i> and use Redux Toolkit's <em>configureStore</em> to create the store.
697
699
698
700
Change the definition of the <i>filter reducer and action creators</i> to use the Redux Toolkit's <em>createSlice</em> function.
699
701
700
702
Also, start using Redux DevTools to debug the application's state easier.
701
703
702
-
#### 6.11 Better anecdotes, step9
704
+
#### 6.11 Better Anecdotes, step 9
703
705
704
706
Change also the definition of the <i>anecdote reducer and action creators</i> to use the Redux Toolkit's <em>createSlice</em> function.
705
707
706
-
#### 6.12 Better anecdotes, step10
708
+
#### 6.12 Better Anecdotes, step 10
707
709
708
710
The application has a ready-made body for the <i>Notification</i> component:
709
711
@@ -748,7 +750,7 @@ You will have to make changes to the application's existing reducer. Create a se
748
750
749
751
The application does not have to use the <i>Notification</i> component intelligently at this point in the exercises. It is enough for the application to display the initial value set for the message in the <i>notificationReducer</i>.
750
752
751
-
#### 6.13 Better anecdotes, step11
753
+
#### 6.13 Better Anecdotes, step 11
752
754
753
755
Extend the application so that it uses the <i>Notification</i> component to display a message for five seconds when the user votes for an anecdote or creates a new anecdote:
El parámetro <em>name</em> de la función <em>createSlice</em> define el prefijo que se utiliza en los valores de tipo de la acción. Por ejemplo, la acción <em>createNote</em> definida más adelante tendrá el valor de tipo <em>notes/createNote</em>. Es una buena práctica dar al parámetro un valor que sea único entre los reducers. De esta forma no habrá colisiones inesperadas entre los valores de tipo de acción de la aplicación. El parámetro <em>initialState</em> define el estado inicial del reducer. El parámetro <em>reducers</em> toma el propio reducer como un objeto, cuyas funciones manejan los cambios de estado causados por ciertas acciones. Tenga en cuenta que <em>action.payload</em> en la función contiene el argumento proporcionado al llamar al creador de la acción:
517
+
El parámetro <em>name</em> de la función <em>createSlice</em> define el prefijo que se utiliza en los valores de tipo de la acción. Por ejemplo, la acción <em>createNote</em> definida más adelante tendrá el valor de tipo <em>notes/createNote</em>. Es una buena práctica dar al parámetro un valor que sea único entre los reducers. De esta forma no habrá colisiones inesperadas entre los valores de tipo de acción de la aplicación.
518
+
El parámetro <em>initialState</em> define el estado inicial del reducer.
519
+
El parámetro <em>reducers</em> toma al propio reducer como un objeto, cuyas funciones manejan los cambios de estado causados por ciertas acciones. Ten en cuenta que <em>action.payload</em> en la función contiene el argumento proporcionado al llamar al creador de la acción:
518
520
519
521
```js
520
522
dispatch(createNote('Redux Toolkit is awesome!'))
521
523
```
522
524
523
-
Esta llamada de <em>dispatch</em> responde al despacho del siguiente objeto:
525
+
Esta llamada a dispatch equivale a enviar el siguiente objeto:
524
526
525
527
```js
526
528
dispatch({ type:'notes/createNote', payload:'Redux Toolkit is awesome!' })
527
529
```
528
530
529
-
Si has seguido todo de cerca, es posible que hayas notado que dentro de la acción <em>createNote</em>, parece suceder algo que viola el principio de inmutabilidad de los reducers mencionado anteriormente:
531
+
Si has prestado atención, es posible que hayas notado que dentro de la acción <em>createNote</em>, parece suceder algo que viola el principio de inmutabilidad de los reducers mencionado anteriormente:
530
532
531
533
```js
532
534
createNote(state, action) {
@@ -540,11 +542,11 @@ createNote(state, action) {
540
542
}
541
543
```
542
544
543
-
Estamos mutando el arreglo del parámetro <em>state</em> llamando al método <em>push</em> en lugar de devolver una nueva instancia del arreglo. ¿De qué se trata todo esto?
545
+
Estamos mutando el array del argumento <em>state</em> al llamar al método <em>push</em> en lugar de devolver una nueva instancia del array. ¿De qué se trata todo esto?
544
546
545
-
Redux Toolkit utiliza la librería [Immer](https://immerjs.github.io/immer/) con reducers creados por la función <em>createSlice</em>, que hace posible mutar el parámetro del <em>estado</em> dentro del reducer. Immer usa el estado mutado para producir un nuevo estado inmutable y, por lo tanto, los cambios de estado permanecen inmutables. Tenga en cuenta que el <em>estado</em> se puede cambiar sin "mutarlo", como hemos hecho con la acción <em>toggleImportanceOf</em>. En este caso, la función <i>retorna</i> el nuevo estado. Sin embargo, mutar el estado a menudo será útil, especialmente cuando se necesita actualizar un estado complejo.
547
+
Redux Toolkit utiliza la librería [Immer](https://immerjs.github.io/immer/) con reducers creados por la función <em>createSlice</em>, lo que hace posible mutar el argumento <em>state</em> dentro del reducer. Immer usa el estado mutado para producir un nuevo estado inmutable y, por lo tanto, los cambios de estado permanecen inmutables. Ten en cuenta que <em>state</em> se puede cambiar sin "mutarlo", como hemos hecho con la acción <em>toggleImportanceOf</em>. En este caso, la función <i>devuelve</i> el nuevo estado directamente. Sin embargo, mutar el estado a menudo será útil, especialmente cuando se necesita actualizar un estado complejo.
546
548
547
-
La función <em>createSlice</em> retorna un objeto que contiene el reducer así como los creadores de acciones definidos por el parámetro <em>reducers</em>. Se puede acceder al reducer mediante la propiedad <em>noteSlice.reducer</em>, mientras que a los creadores de acciones mediante la propiedad <em>noteSlice.actions</em>. Podemos producir las exportaciones del archivo de la siguiente manera:
549
+
La función <em>createSlice</em> devuelve un objeto que contiene al reducer así como a los action creators definidos por el parámetro <em>reducers</em>. Se puede acceder al reducer mediante la propiedad <em>noteSlice.reducer</em>, mientras que a los action creators mediante la propiedad <em>noteSlice.actions</em>. Podemos producir las exportaciones del archivo de la siguiente manera:
548
550
549
551
```js
550
552
constnoteSlice=createSlice(/* ... */)
@@ -562,9 +564,9 @@ Las importaciones en otros archivos funcionarán igual que antes:

655
657
656
-
La salida es interesante pero no muy útil. Esto trata de la librería Immer mencionada anteriormente utilizada por Redux Toolkit, que ahora se usa internamente para guardar el estado de la Tienda.
658
+
Lo que vemos es interesante pero no muy útil. Esto tiene que ver con la librería Immer que mencionamos anteriormente y es utilizada por Redux Toolkit internamente para guardar el estado de la Tienda.
657
659
658
-
El estado se puede convertir a un formato legible por humanos, e.j. convirtiéndolo en una cadena y de nuevo en un objeto JavaScript de la siguiente manera:
660
+
El estado se puede convertir a un formato legible por humanos, por ejemplo, convirtiéndolo primero en un string y luego de nuevo en un objeto JavaScript de la siguiente manera:
La salida de la consola ahora es legible para humanos
666
+
Ahora lo que imprime la consola es legible para humanos
665
667
666
-

668
+

667
669
668
670
### Redux DevTools
669
671
670
672
[Redux DevTools](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd) es una extension de Chrome, que ofrece útiles herramientas de desarrollo para Redux. Se puede usar, por ejemplo, para inspeccionar el estado del store de Redux y enviar acciones (dispatch) a través de la consola del navegador. Cuando el store se crea usando la función <em>configureStore</em> de Redux Toolkit, no se necesita ninguna configuración adicional para que Redux DevTools funcione.
671
673
672
-
Una vez instalado el complemento, al hacer clic en la pestaña de Redux en la consola del navegador deberia abrir las herramientas de desarrollo:
674
+
Una vez instalada la extension, al hacer clic en la pestaña de <i>Redux</i> en las herramientas de desarrollo del navegador, Redux DevTools debería abrirse:
673
675
674
-

676
+

675
677
676
678
Puedes inspeccionar cómo el envío de una determinada acción cambia el estado haciendo clic en la acción:
677
679
678
-

680
+

679
681
680
682
También es posible enviar acciones (dispatch) a la store utilizando las herramientas de desarrollo:
681
683
682
-

684
+

683
685
684
-
El código actual de la aplicación estan en la rama <i>part6-3</i> de [este repositorio de Github](https://github.com/fullstack-hy2020/redux-notes/tree/part6-3).
686
+
El código actual de la aplicación se puede encontrar en [GitHub](https://github.com/fullstack-hy2020/redux-notes/tree/part6-3), en la rama <i>part6-3</i>.
685
687
686
688
</div>
687
689
688
690
<div class="tasks">
689
691
690
-
691
692
### Ejercicios 6.10.-6.13.
692
693
693
694
Continuemos trabajando en la aplicación de anécdotas que comenzamos en el ejercicio 6.3, usando Redux Toolkit.
694
695
695
-
#### 6.10 Mejores anécdotas, paso 8
696
+
#### 6.10 Mejores Anécdotas, paso 8
696
697
697
-
Instale Redux Toolkit en el proyecto. Mueva la creación de la store de redux a su propio archivo <i>store.js</i> y use la función <em>configureStore</em> para crear la store.
698
+
Instala Redux Toolkit en el proyecto. Mueve la creación del store de Redux a su propio archivo <i>store.js</i> y utiliza la función <em>configureStore</em> para crear el store.
698
699
699
-
Cambie la definición del <i>Filter reducer y creación de acciones</i> para usar la función <em>createSlice</em> de Redux Toolkit.
700
+
Cambia la definición del <i>filter reducer y sus action creators</i> para usar la función <em>createSlice</em> de Redux Toolkit.
700
701
701
-
También, empiece a usar los Redux DevTools para depurar el estado de la aplicación fácilmente.
702
+
También, comienza a utilizar Redux DevTools para depurar el estado de la aplicación fácilmente.
702
703
703
-
#### 6.11 Mejores anécdotas, paso 9
704
+
#### 6.11 Mejores Anécdotas, paso 9
704
705
705
-
Cambie también la definición de <i>Anecdote reducer y creación de acciones</i> para usar la función <em>createSlice</em> de Redux Toolkit.
706
+
Cambia también la definición de <i>anecdote reducer y sus action creators</i> para usar la función <em>createSlice</em> de Redux Toolkit.
706
707
707
-
#### 6.12 Mejores anécdotas, paso 10
708
+
#### 6.12 Mejores Anécdotas, paso 10
708
709
709
-
La aplicación tiene un cuerpo listo para usar el componente <i>Notification</i>:
710
+
La aplicación tiene el esqueleto del componente <i>Notification</i> listo para utilizarlo:
710
711
711
712
```js
712
713
constNotification= () => {
@@ -725,7 +726,7 @@ const Notification = () => {
725
726
exportdefaultNotification
726
727
```
727
728
728
-
Extienda el componente para que muestre el mensaje almacenado en el store de redux, haciendo que el componente tome la siguiente forma:
729
+
Extiende el componente para que muestre el mensaje almacenado en el store de redux, haciendo que el componente tome la siguiente forma:
Tendrá que realizar cambios en el reducer existente de la aplicación. Cree un reducer separado para la nueva funcionalidad usando la función <em>createSlice</em> de Redux Toolkit.
749
+
Tendrás que realizar cambios en el reducer existente de la aplicación. Crea un reducer separado para la nueva funcionalidad usando la función <em>createSlice</em> de Redux Toolkit.
749
750
750
751
La aplicación no tiene que utilizar el componente <i>Notification</i> completamente en este punto de los ejercicios. Es suficiente con que la aplicación muestre el valor inicial establecido para el mensaje en el <i>notificationReducer</i>.
751
752
752
-
#### 6.13 Mejores anécdotas, paso 11
753
+
#### 6.13 Mejores Anécdotas, paso 11
753
754
754
-
Extienda la aplicación para que utilice el componente <i>Notification</i> para mostrar un mensaje durante cinco segundos cuando el usuario vote por una anécdota o cree una nueva anécdota:
755
+
Extiende la aplicación para que utilice el componente <i>Notification</i> para mostrar un mensaje durante cinco segundos cuando el usuario vote por una anécdota o cree una nueva anécdota:
755
756
756
-

757
+

757
758
758
-
Se recomienda crear [creadores de acciones](https://redux-toolkit.js.org/api/createSlice#reducers) independientes para configurar y eliminar notificaciones.
759
+
Se recomienda crear [action creators](https://redux-toolkit.js.org/api/createSlice#reducers) independientes para configurar y eliminar notificaciones.
0 commit comments