{"id":1719,"date":"2024-08-02T11:19:05","date_gmt":"2024-08-02T09:19:05","guid":{"rendered":"https:\/\/blog.sutilweb.eu\/?page_id=1719"},"modified":"2024-08-02T11:19:07","modified_gmt":"2024-08-02T09:19:07","slug":"006-componentes-con-estado","status":"publish","type":"page","link":"https:\/\/sutilweb.eu\/index.php\/lenguajes\/javascript\/javascript-practico\/19-reactividad\/006-componentes-con-estado\/","title":{"rendered":"006. Componentes con Estado"},"content":{"rendered":"\n<p>En esta filosof\u00eda de <strong>programaci\u00f3n reactiva y orientada a componentes<\/strong>, cada pedacito de la <strong>UI<\/strong> puede ser un componente y a su vez ese componente tener una <strong>UI propiab<\/strong>. En este cap\u00edtulo haremos que nuestros <strong>componentes<\/strong> tengan un <strong>estado<\/strong> o <strong>componente local<\/strong>.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>Vamos a crear un archivo denominado <em>04_componentes-con-estado.html<\/em>, que tiene la siguiente sintaxis.<\/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;Componentes con Estado&lt;\/title&gt;\n&nbsp; &lt;\/head&gt;\n\n&nbsp; &lt;body&gt;\n&nbsp; &nbsp; &lt;h1&gt;Componentes con 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&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 Global\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 UI\n&nbsp; &nbsp; &nbsp; const template = () =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; if (template.data.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 = template.data.todoList\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map((item) =&gt; `&lt;li&gt;${item}&lt;\/li&gt;`)\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .join(\"\");\n&nbsp; &nbsp; &nbsp; &nbsp; return todos;\n&nbsp; &nbsp; &nbsp; };\n\n&nbsp; &nbsp; &nbsp; \/\/ Agregar State al Template que genera el componente de UI (State Local)\n&nbsp; &nbsp; &nbsp; template.data = {\n&nbsp; &nbsp; &nbsp; &nbsp; todoList: [],\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(\"Estado global\", state);\n&nbsp; &nbsp; &nbsp; &nbsp; console.log(\"Estado local\", template.data);\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 (template.data.hasOwnProperty(key)) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; template.data[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(template.data));\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; });\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 esta filosof\u00eda de programaci\u00f3n reactiva y orientada a componentes, cada pedacito de la UI puede ser un componente y [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1703,"menu_order":5,"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-1719","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 esta filosof\u00eda de programaci\u00f3n reactiva y orientada a componentes, cada pedacito de la UI puede ser un componente y [&hellip;]","_links":{"self":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1719","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=1719"}],"version-history":[{"count":2,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1719\/revisions"}],"predecessor-version":[{"id":1721,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1719\/revisions\/1721"}],"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=1719"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}