{"id":1713,"date":"2024-08-02T11:17:25","date_gmt":"2024-08-02T09:17:25","guid":{"rendered":"https:\/\/blog.sutilweb.eu\/?page_id=1713"},"modified":"2024-08-02T11:17:26","modified_gmt":"2024-08-02T09:17:26","slug":"004-estado-reactivo","status":"publish","type":"page","link":"https:\/\/sutilweb.eu\/index.php\/lenguajes\/javascript\/javascript-practico\/19-reactividad\/004-estado-reactivo\/","title":{"rendered":"004. Estado Reactivo"},"content":{"rendered":"\n<p>En el cap\u00edtulo anterior empezamos a implementar el concepto del <strong>estado<\/strong>, transformando un peque\u00f1o ejercicio de <strong>manipulaci\u00f3n del DOM tradicional<\/strong> en <strong>Javascript<\/strong>, agregando este concepto del estado, tener un <strong>template UI<\/strong> y una funci\u00f3n que renderice.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>Sin embargo estamos trabajando directamente con el <strong>state<\/strong> (<strong>estado<\/strong>), y esto, en <strong>librer\u00edas<\/strong> o <strong>frameworks<\/strong> reactivos como <a href=\"https:\/\/es.react.dev\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>React<\/strong> <\/a>o <a href=\"https:\/\/angular.io\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Angular<\/strong> <\/a>no est\u00e1 bien visto, por lo que en el ejercicio que pondremos en este cap\u00edtulo vamos a hacer que el <strong>estado<\/strong> se actualice de <strong>manera reactiva<\/strong>, de hecho, si se ha trabajado con <strong>React<\/strong> se ver\u00e1n muchas coincidencias en la manera como <strong>React<\/strong> actualiza el <strong>estado<\/strong> en aplicaciones basadas en esta <strong>librer\u00eda.<\/strong><\/p>\n\n\n\n<p>El detalle de hacer reactivo nuestro <strong>estado<\/strong> es evitar manipularlo directamente, as\u00ed que lo que haremos ser\u00e1 crear un <strong>m\u00e9todo<\/strong> que nos permita manipular el <strong>state<\/strong> de manera <strong>reactiva.<\/strong><\/p>\n\n\n\n<p>En una <strong>programaci\u00f3n basada en el estado<\/strong> es muy importante que al inicio de nuestra aplicaci\u00f3n consideremos todas las posibles <strong>variables<\/strong> que justamente van a formar parte de ese <strong>estado,<\/strong> para que, ya sea por interacciones del usuario o por interacciones que se hagan m\u00e1s adelante, nuestro <strong>estado<\/strong> no se vea afectado por valores que no necesitemos en un principio. Por lo tanto, cada <strong>propiedad<\/strong> que vayamos a trabajar en el <strong>estado<\/strong> de nuestra <strong>aplicaci\u00f3n<\/strong> la definimos al inicio, aunque no tenga valor, y gracias al m\u00e9todo <em>setState()<\/em> evaluamos que la tenga y si la tiene la actualiza, y si no nuestro <strong>estado<\/strong> la est\u00e1 ignorando, y de esta manera protegemos la <strong>integridad del estado<\/strong> de nuestra <strong>aplicaci\u00f3n.<\/strong> Es por ello que es importante hacer el cambio con la funci\u00f3n <em>setState()<\/em> y no trabajar directamente en el estado.<\/p>\n\n\n\n<p>Una de las <strong>propiedades,<\/strong> como dijimos en cap\u00edtulos anteriores, es que <strong>el estado tiene que permanecer inmutable<\/strong>, es decir, que cualquier persona no lo pueda modificar, es por ello que la funci\u00f3n <em>setState()<\/em> es la que se encarga de modificarlo.<\/p>\n\n\n\n<p>Vamos a crear un archivo nuevo denominado <em>01_reactividad-estado.js.<\/em><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!DOCTYPE html&gt;\n&lt;html lang=\"es\"&gt;\n&nbsp; &lt;head&gt;\n&nbsp; &nbsp; &lt;meta charset=\"UTF-8\" \/&gt;\n&nbsp; &nbsp; &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" \/&gt;\n&nbsp; &nbsp; &lt;title&gt;Reactividad del Estado&lt;\/title&gt;\n&nbsp; &lt;\/head&gt;\n\n&nbsp; &lt;body&gt;\n&nbsp; &nbsp; &lt;h1&gt;Reactividad del Estado&lt;\/h1&gt;\n\n&nbsp; &nbsp; &lt;form id=\"todo-form\"&gt;\n&nbsp; &nbsp; &nbsp; &lt;input type=\"text\" id=\"todo-item\" placeholder=\"Tarea por hacer\" \/&gt;\n&nbsp; &nbsp; &nbsp; &lt;input type=\"submit\" value=\"Agregar\" \/&gt;\n&nbsp; &nbsp; &lt;\/form&gt;\n\n&nbsp; &nbsp; &lt;h2&gt;Lista de tareas&lt;\/h2&gt;\n\n&nbsp; &nbsp; &lt;ul id=\"todo-list\"&gt;&lt;\/ul&gt;\n\n&nbsp; &nbsp; &lt;script&gt;\n&nbsp; &nbsp; &nbsp; const d = document;\n\n&nbsp; &nbsp; &nbsp; \/\/ El State\n&nbsp; &nbsp; &nbsp; const state = {\n&nbsp; &nbsp; &nbsp; &nbsp; todoList: [],\n&nbsp; &nbsp; &nbsp; &nbsp; nombre: \"\",\n&nbsp; &nbsp; &nbsp; };\n\n&nbsp; &nbsp; &nbsp; \/\/ Template\n&nbsp; &nbsp; &nbsp; const template = () =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; if (state.todoList.length &lt; 1) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return `&lt;p&gt;&lt;em&gt;Lista sin tareas por hacer&lt;\/em&gt;&lt;\/p&gt;`;\n&nbsp; &nbsp; &nbsp; &nbsp; }\n\n&nbsp; &nbsp; &nbsp; &nbsp; let todos = state.todoList.map((item) =&gt; `&lt;li&gt;${item}&lt;\/li&gt;`).join(\"\");\n\n&nbsp; &nbsp; &nbsp; &nbsp; return todos;\n&nbsp; &nbsp; &nbsp; };\n\n&nbsp; &nbsp; &nbsp; \/\/ Render UI\n&nbsp; &nbsp; &nbsp; const render = () =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; console.log(state);\n&nbsp; &nbsp; &nbsp; &nbsp; const $list = d.getElementById(\"todo-list\");\n&nbsp; &nbsp; &nbsp; &nbsp; if (!$list) return;\n&nbsp; &nbsp; &nbsp; &nbsp; $list.innerHTML = template();\n&nbsp; &nbsp; &nbsp; };\n\n&nbsp; &nbsp; &nbsp; \/\/ Actualizar el State de manera reactiva\n&nbsp; &nbsp; &nbsp; const setState = (obj) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; for (let key in obj) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (state.hasOwnProperty(key)) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; state[key] = obj[key];\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }\n&nbsp; &nbsp; &nbsp; &nbsp; }\n\n&nbsp; &nbsp; &nbsp; &nbsp; render();\n&nbsp; &nbsp; &nbsp; };\n\n&nbsp; &nbsp; &nbsp; d.addEventListener(\"DOMContentLoaded\", render);\n\n&nbsp; &nbsp; &nbsp; \/\/ Estableciendo valores por defecto al state\n&nbsp; &nbsp; &nbsp; setState({\n&nbsp; &nbsp; &nbsp; &nbsp; todoList: [\"Tarea 1\", \"Tarea 2\", \"Tarea 3\"],\n&nbsp; &nbsp; &nbsp; &nbsp; nombre: \"Francisco\",\n&nbsp; &nbsp; &nbsp; });\n\n&nbsp; &nbsp; &nbsp; \/\/ Estado mutable, ya que permite modificar el estado directamente creando una copia del objeto y agregando otro elemento\n&nbsp; &nbsp; &nbsp; const items = state.todoList;\n&nbsp; &nbsp; &nbsp; items.push(\"Tarea 10\");\n\n&nbsp; &nbsp; &nbsp; d.addEventListener(\"submit\", (e) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; if (!e.target.matches(\"#todo-form\")) return false;\n&nbsp; &nbsp; &nbsp; &nbsp; e.preventDefault();\n\n&nbsp; &nbsp; &nbsp; &nbsp; const $item = d.getElementById(\"todo-item\");\n\n&nbsp; &nbsp; &nbsp; &nbsp; if (!$item) return;\n\n&nbsp; &nbsp; &nbsp; &nbsp; \/\/ Actualizar el State y la UI\n&nbsp; &nbsp; &nbsp; &nbsp; state.todoList.push($item.value);\n&nbsp; &nbsp; &nbsp; &nbsp; render();\n\n&nbsp; &nbsp; &nbsp; &nbsp; \/\/ Limpiar el input\n&nbsp; &nbsp; &nbsp; &nbsp; $item.value = \"\";\n&nbsp; &nbsp; &nbsp; &nbsp; $item.focus();\n&nbsp; &nbsp; &nbsp; });\n&nbsp; &nbsp; &lt;\/script&gt;\n&nbsp; &lt;\/body&gt;\n&lt;\/html&gt;<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>En el cap\u00edtulo anterior empezamos a implementar el concepto del estado, transformando un peque\u00f1o ejercicio de manipulaci\u00f3n del DOM tradicional [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1703,"menu_order":3,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"class_list":["post-1713","page","type-page","status-publish","hentry"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Sutil Web","author_link":"https:\/\/sutilweb.eu\/index.php\/author\/sutilweb\/"},"uagb_comment_info":0,"uagb_excerpt":"En el cap\u00edtulo anterior empezamos a implementar el concepto del estado, transformando un peque\u00f1o ejercicio de manipulaci\u00f3n del DOM tradicional [&hellip;]","_links":{"self":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1713","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/comments?post=1713"}],"version-history":[{"count":2,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1713\/revisions"}],"predecessor-version":[{"id":1715,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1713\/revisions\/1715"}],"up":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1703"}],"wp:attachment":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/media?parent=1713"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}