WebReflection / dom-augmentor

Same as augmentor but with DOM oriented useEffect handling via dropEffect.
ISC License
59 stars 2 forks source link

Two effects at once not working? #20

Closed SirPepe closed 4 years ago

SirPepe commented 4 years ago

This may not be a bug but rather my lack of experience with hooks, but I would expect the following to work with dom-augmentor (it does work with React):


// Some hook that sets state when some external callback fires
const usePlus = () => {
  const [ state, setState ] = useState(0);
  const result = useRef(state);
  useEffect( () => {
    console.log("plus effect");
    const handler = () => setState(++result.current);
    document.querySelector(".plus").addEventListener("click", handler);
    return () => {
      console.log("plus cleanup");
      document.querySelector(".plus").removeEventListener("click", handler);
    };
  }, []);
  return state;
};

// The same as usePlus() above
const useMinus = () => {
  const [ state, setState ] = useState(0); 
  const result = useRef(state);
  useEffect( () => {
    console.log("minus effect");
    const handler = () => setState(++result.current);
    document.querySelector(".minus").addEventListener("click", handler);
    return () => {
      console.log("minus cleanup");
      document.querySelector(".minus").removeEventListener("click", handler);
    };
  }, []);
  return state;
};

const Content = () => $(() => {
  const plus = usePlus();   // this has no effect at all
  const minus = useMinus(); // this works
  return html`
    <div>
      +${ plus } / -${ minus } (${ plus - minus })
    </div>
  `;
});

render(document.querySelector(".result"), Content());

The second hook always works while the first one never even registers the click event. Is this intentional? If so, how would I use multiple side effects in my Content component?

WebReflection commented 4 years ago

can you please try useState(0, {async: true}); in both cases and tell me how it goes?

SirPepe commented 4 years ago

Does not change anything.

WebReflection commented 4 years ago

It should just work now 👋

SirPepe commented 4 years ago

Works like a charm, thank you!

WebReflection commented 4 years ago

Thanks, and BTW, you are basically reproducing neverland by your own, maybe worth having a look there ;-)

SirPepe commented 4 years ago

Yeah, but then I'd have to wrangle with TypeScript definitons again, gonna procrastinate on this for now.