How to make useStore detect state change?

32 views Asked by At

It renders a button changing store.a.state.

When I click a button it executes that method and I can check it by console.log.

At the same time I expect the button content is changed to "b", but it remains intact.

What am I missing here?

(noSerialize is required, because it is simplified form of complex code)

import type { NoSerialize } from "@builder.io/qwik";
import {
  component$,
  noSerialize,
  useStore,
  useVisibleTask$,
} from "@builder.io/qwik";
import { css } from "~/styled-system/css";
import { Container } from "~/styled-system/jsx/container";

export default component$(() => {
  const store = useStore<{
    a: NoSerialize<{ state: "a" | "b"; toggle: () => void }> | null;
  }>({ a: null });

  useVisibleTask$(async () => {
    store.a = noSerialize({
      state: "a" as "a" | "b",
      toggle() {
        this.state = this.state === "a" ? "b" : "a";
        console.log(`a.toggle invoked`, this);
      },
    });
  });

  return (
    <Container
      class={css({ display: "flex", flexFlow: "column nowrap", gap: "4" })}
    >
      <button
        class={css({
          rounded: "lg",
          backgroundColor: "green.600",
          cursor: "pointer",
          color: "white",
          padding: "1",
          _hover: { backgroundColor: "green.500" },
          _active: { backgroundColor: "green.400" },
        })}
        onClick$={() => store.a?.toggle()}
      >
        {store.a?.state}
      </button>
    </Container>
  );
});
0

There are 0 answers