#useComputed$ strange behavior or is it me

7 messages · Page 1 of 1 (latest)

spare wolf
#

Hey guys, I already submitted an issue on GitHub (https://github.com/BuilderIO/qwik/issues/4868) but I just want to make sure that I am not doing anything wrong.

Here is the stackblitz reproduction: https://stackblitz.com/edit/qwik-starter-ttztwp?file=src%2Fcomponents%2Fbig-card.tsx

In short there are 2 components , BigCard and Card.

BigCard has a constant (noImg) that is used as a fallback if there is no src.
If the fallback uses static value then the useComputed$ in the Card component works OK, but if the fallback is assigned to another variable/const the useComputed$ will not update the returned value.

Can someone take a look and tell me if I am doing something wrong.

signal flame
#

useComputed needs to wrap a signal. You sending in a string so its not reactive

#

here is an example where I send the signal to Card instead

import { component$, useComputed$, useSignal } from "@builder.io/qwik";

const noImg = "https://placehold.co/100?text=No+image";
const Card = component$((props: { src?: string }) => {
  const src = useComputed$(() => {
    return props.src ? `${props.src}&=test` : `${noImg}&=test`;
  });

  return (
    <div style={{ border: "1px solid white", padding: "1rem" }}>
      <p>Card props.src: {src.value}</p>

      <div>
        <img src={src.value} width={120} height={120} />
      </div>
    </div>
  );
});

const BigCard = component$((props: { data: { id: number; src?: string } }) => {
  return (
    <div
      style={{
        flexDirection: "column",
        border: "1px solid red",
        padding: "1rem",
        gap: "1rem",
      }}>
      <Card src={props.data.src} />
      <div>BigCard {JSON.stringify(props.data)}</div>
    </div>
  );
});

export default component$(() => {
  const data = useSignal<{ id: number; src?: string }>({
    id: 1,
    src: "https://placehold.co/100?text=Has+image",
  });

  return (
    <>
      <button
        onClick$={() => {
          if (data.value.src) {
            data.value = {
              id: data.value.id,
            };
          } else {
            data.value = {
              id: data.value.id,
              src: "https://placehold.co/100?text=Has+image",
            };
          }
        }}>
        {data.value.src ? "Remove image" : "Add image"}
      </button>
      <BigCard data={data.value} />
    </>
  );
});
spare wolf
#

Umm sorry I don't think I understand.

If you comment out big-card.tsx line 11 and uncomment line 14 the useComputed$ works and it does not really care if it is a string or signal

spare wolf
signal flame
spare wolf
#

I dream for a qwik cheatsheet that references what reacts to what and is and is not serializable 😁