{"id":1716,"date":"2024-08-02T11:18:22","date_gmt":"2024-08-02T09:18:22","guid":{"rendered":"https:\/\/blog.sutilweb.eu\/?page_id=1716"},"modified":"2024-08-02T11:18:23","modified_gmt":"2024-08-02T09:18:23","slug":"005-estado-inmutable","status":"publish","type":"page","link":"https:\/\/sutilweb.eu\/index.php\/lenguajes\/javascript\/javascript-practico\/19-reactividad\/005-estado-inmutable\/","title":{"rendered":"005. Estado Inmutable"},"content":{"rendered":"\n<p>En el cap\u00edtulo anterior logramos que nuestro <strong>estado<\/strong> reaccionara de manera reactiva y renderizara la <strong>UI<\/strong>, sin embargo todav\u00eda es un <strong>estado mutable<\/strong>, es decir, podemos acceder directamente al <strong>state<\/strong> y modificarlo, y el objetivo de un estado es su inmutabilidad.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>Para poder hacer un <strong>estado inmutable<\/strong>, lo que vamos a hacer en este cap\u00edtulo es, antes de actualizar el <strong>estado<\/strong>, obtener una copia de ese estado. Crearemos una nueva funci\u00f3n que nos va a permitir obtener una copia inmutable del estado, la funci\u00f3n es <em>getState()<\/em>.<\/p>\n\n\n\n<p>Vamos a crear un archivo que se llame <em>03_estado-inmutable.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;Estado inmutable&lt;\/title&gt;\n&nbsp; &lt;\/head&gt;\n\n&nbsp; &lt;body&gt;\n&nbsp; &nbsp; &lt;h1&gt;Estado inmutable&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&nbsp; &nbsp; &nbsp; &nbsp; let todos = state.todoList.map((item) =&gt; `&lt;li&gt;${item}&lt;\/li&gt;`).join(\"\");\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&nbsp; &nbsp; &nbsp; &nbsp; render();\n&nbsp; &nbsp; &nbsp; };\n\n&nbsp; &nbsp; &nbsp; \/\/ Obteniendo una copia inmutable del State\n&nbsp; &nbsp; &nbsp; const getState = () =&gt; JSON.parse(JSON.stringify(state));\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 = getState();\n&nbsp; &nbsp; &nbsp; \/\/ items.push(\"Tarea 10\");\n&nbsp; &nbsp; &nbsp; items.todoList.push(\"Tarea 100\");\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&nbsp; &nbsp; &nbsp; &nbsp; const $item = d.getElementById(\"todo-item\");\n&nbsp; &nbsp; &nbsp; &nbsp; if (!$item) return;\n\n&nbsp; &nbsp; &nbsp; &nbsp; \/\/ Actualizar el State de forma reactiva\n&nbsp; &nbsp; &nbsp; &nbsp; const lastState = getState();\n&nbsp; &nbsp; &nbsp; &nbsp; lastState.todoList.push($item.value);\n\n&nbsp; &nbsp; &nbsp; &nbsp; setState({\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; todoList: lastState.todoList,\n&nbsp; &nbsp; &nbsp; &nbsp; });\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 logramos que nuestro estado reaccionara de manera reactiva y renderizara la UI, sin embargo todav\u00eda es [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1703,"menu_order":4,"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-1716","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 logramos que nuestro estado reaccionara de manera reactiva y renderizara la UI, sin embargo todav\u00eda es [&hellip;]","_links":{"self":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1716","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=1716"}],"version-history":[{"count":2,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1716\/revisions"}],"predecessor-version":[{"id":1718,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1716\/revisions\/1718"}],"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=1716"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}