WebReflection / hyperHTML

A Fast & Light Virtual DOM Alternative
ISC License
3.06k stars 112 forks source link

What am I doing wrong? #385

Closed AmandaOliver closed 4 years ago

AmandaOliver commented 4 years ago

Hello!, I'm quite new with hyperHTML, and I cannot wrap my head around conditional rendering of wires just yet. I have some cases when depending on some application state I do not want to render a specific wire at all, in those cases I'm using a structure like this: const nestedWire = this.state.showNested ? this.renderNestedWire() : ''; which is giving me headaches when having several nested wires, as sometimes the parent doesn't detect changes.

While trying to recreate the issue i'm having with nested wires I've put up a code example that isn't re-rendering when the reference object is updated, I've followed the debugger and hyperHTML IS detecting changes and returning the correct wired content in the render function. But the bind "isn't picking it up" so the content is not being updated. To test it just execute showNestedToggle(false) from the console.

So my questions would be:

  1. how to handle conditional rendering of wires properly
  2. what is wrong in this code?

I am afraid I am doing something terribly wrong, I just cannot understand what.

Edit optimistic-greider-p96bb

WebReflection commented 4 years ago

The following seems to work for me, and the thing is that you need to update the bound content too, and it should be through a callback, otherwise the template literal is different (even if it looks the same).

const {bind, wire} = require("hyperhtml");

window.showNested = true;
window.showNestedToggle = state => {
  window.showNested = state;
  update();
};
function Test() {
  this.state = {
    showNested: window.showNested
  };
}
Test.prototype = {
  renderNestedWire: function() {
    return wire(this.state, ":nestedid")`<p>hello from nested</p>`;
  },
  render: function() {
    this.state = {
      showNested: window.showNested
    };
    const nestedWire = this.state.showNested ? this.renderNestedWire() : "";
    const anotherNestedWire = wire(
      this.state,
      ":anothernestedid"
    )`<p>hello from another nested</p>`;
    return wire(this.state, ":testid")`
            <div>
                ${nestedWire}
                ${anotherNestedWire}
            </div>
        `;
  }
};
const test = new Test();
const view = bind(window.document.body.querySelector("#app"));
update();
function update() {
  view`${test.render()}`;
}

setInterval(() => { window.showNestedToggle(!window.showNested); }, 2000);
AmandaOliver commented 4 years ago

Thanks a lot ! :D